JavaScript - Like a Box of Chocolates - jsDay
-
date post
17-Oct-2014 -
Category
Technology
-
view
4.620 -
download
2
description
Transcript of JavaScript - Like a Box of Chocolates - jsDay
JavaScriptLike a Box of Chocolates
@robertnyman
http://robertnyman.com
“Are you telling me that I can’t get away anymore without getting deeply into Javascript?”
- Developer
“That is a disaster for me! I have made a career out of actively avoiding Javascript.”
- Developer
“If I cant continue to ignore Javascript, then you may as well amputate one of my limbs.”
- Developer
// Various "false" valuesvar nullVal = null;var undefinedVal = undefined;var zeroVal = 0;var falseVal = false;var emptyString = "";
// All would equal false in an if-clauseif (emptyString) { // Would never go in here}
“Coercion is the practice of forcing another party to behave in an involuntary manner”
- Wikipedia
// Equalityif (7 == "7") { // true}
// Identityif (7 === "7") { // false}
Type coercio
n
// Type coercionvar sum = "5" + 6 + 7; // 567
// Prevent type coercionvar sum = parseInt("5", 10) + 6 + 7; // 18
// Self-invoking functions(function () { var investment = "Lieutenant Dan got me invested in some kind of fruit company.";})();
// Using argumentsfunction friends (friend1, friend2) { return friend1 + " & " + friend2;}
// Lieutenant Dan & Bubbafriends("Lieutenant Dan", "Bubba");
// Lieutenant Dan & undefinedfriends("Lieutenant Dan");
// Using the arguments collectionfunction friends () { var allFriends = []; for (var i=0, il=arguments.length; i<il; i++) { allFriends.push(arguments[i]); }; return allFriends.join(" & ");}
// Lieutenant Dan & Bubbafriends("Lieutenant Dan", "Bubba");
// Lieutenant Danfriends("Lieutenant Dan");
// Object declarationfunction Forrest () { this.firstName = "Forrest"; this.lastName = "Gump";}
var forrest = new Forrest();
// Object declaration, literal stylevar forrest = { firstName : "Forrest", lastName : "Gump"};
// Iterating over propertiesfor (var item in forrest) { console.log(item + ": " + forrest[item]);}
// Object declarationvar forrest = { firstName : "Forrest"};
// Safe check for propertyif ("firstName" in forrest) { console.log(forrest.firstName);}
// Object declarationfunction ForrestAsChild { this.firstName = "Forrest";};
// Method set via prototypeForrestAsChild.prototype.runsFast = function () { return true;};
// Object declarationfunction ForrestAsGrownup { this.joinsArmy = true;};
// Prototype for new objectForrestAsGrownup.prototype = new ForrestAsChild;
// Method set via prototypeForrestAsGrownup.prototype.ruinsBathrobe = function () { return "I think I ruined your roommate's bathrobe";};
// Create an instancevar forrest = new ForrestAsGrownup();
// Returns "I think I ruined your roommate's bathrobe"forrest.ruinsBathrobe();
// Returns true - from ForrestAsChildforrest.runsFast();
// Failsforrest.codesJavaScript();
forrest instance
ForrestAsGrownup
ForrestAsChild
Object
// Extending core JavaScript objectsif (typeof Array.prototype.push === "undefined") { Array.prototype.push = function () { for (var i=0, il=arguments.length; i<il; i++) { this[this.length] = arguments[i]; }; return this; }}
var locations = ["Vietnam"];locations.push("China", "White House");// locations = ["Vietnam", "China", "White House"];
// Scope - global or local
// Globalvar quote = "I had run for 3 years, 2 months, 14 days, and 16 hours."
function () { // Local var pantherParty = "I'm sorry I had to fight in the middle of your Black Panther party."; // Global question = "And so, you just ran?";}
// Globalfunction meetingJFK () { var JFKQuestion = "Congratulations, how do you feel?"; // Local function forrestReply () { return "I gotta pee."; } return forrestReply();}
meetingJFK(); // I gotta peeforrestReply(); // Error: not accessible
// Controlling scopefunction whoAmI () { return this.nodeName;}
whoAmI(); // undefinedwhoAmI.call(document, "Hello"); // #documentwhoAmI.apply(document.body, ["Hello", "Greetings?"]); // BODY
// closuresfunction happens (what) { return function (verb) { return what + " " + verb; }}
var action = happens("Shit");
action("happens"); // Shit happens
// closuresfunction happens (what) { return function (verb) { return what + " " + verb; }}
var action = happens("Shit");
// Breaking it downvar action = function (verb) { return "Shit" + " " + verb;};
var link;for (var i=0; i<3; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function () { alert("I am link " + i); }; document.body.appendChild(link);};
var link;for (var i=0; i<3; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (index) { return function () { alert("I am link " + index); }; }(i); document.body.appendChild(link);};
// Yahoo! JavaScript Module Patternvar forrest = function () { var firstName = "Forrest"; return { getFirstName : function () { return firstName; } };}();
// Returns "Forrest"forrest.getFirstName();
// Yahoo! JavaScript Module Patternvar forrest = function () { var firstName = "Forrest", getFirstName = function () { return firstName; }; return { getFirstName : getFirstName };}();
// Returns "Forrest"forrest.getFirstName();
// Namespacingvar Movie = {};
// Yahoo! JavaScript Module PatternMovie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } };}();
// Yahoo! JavaScript Module PatternMovie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } };}();
// Yahoo! JavaScript Module PatternMovie.lieutenantDan = function () { var lastName = "Taylor"; return { firstName : "Dan", getFullName : function () { return Movie.forrest.getFirstName.call(this) + " " + lastName; } };}();
Movie.lieutenantDan.getFullName();
// Minimize DOM accessdocument.getElementById("container").className = "js-enabled";document.getElementById("container").innerHTML += "Hello Verona";document.getElementById("container").innerHTML += "Tell me how you doin'!";document.getElementById("container").innerHTML += "Lovely to be here...";document.getElementById("container").innerHTML += "...at a World Heritage Site";
// Minimize DOM accessvar container = document.getElementById("container"), content = "Hello Verona";container.className = "js-enabled";content += "Tell me how you doin'!";content += "Lovely to be here...";content += "...at a World Heritage Site";container.innerHTML = content;
// Looping, variables and array lookupsfunction forrestForm () { var allParagraphs = document.getElementsByTagName("p"); for (var i=0; i<allParagraphs.length; i++) { var link = document.createElement("a"); link.href = "http://en.wikipedia.org/wiki/Forrest_Gump"; link.title = "Read about Forrest Gump at Wikipedia"; link.innerHTML = "Forrest Gump";
allParagraphs[i].className = "Forrested"; allParagraphs[i].appendChild(link); }}
// Looping, variables and array lookupsfunction forrestForm () { var allParagraphs = document.getElementsByTagName("p"); for (var i=0, l=allParagraphs.length, link, paragraph; i<l; i++) { link = document.createElement("a"); link.href = "http://en.wikipedia.org/wiki/Forrest_Gump"; link.title = "Read about Forrest Gump at Wikipedia"; link.innerHTML = "Forrest Gump"; paragraph = allParagraphs[i]; paragraph.className = "Forrested"; paragraph.appendChild(link); }}
// Variable declarationfunction richAndStupid () { var rich = "And cause I was a gazillionaire, I cut that grass for free.", stupid = "Stupid is as stupid does.";}
if (!("a" in window)) { var a = 1;}alert(a); // undefined
function value () { return 1;}var value;alert(typeof value); // function
function value () { return 1;}var value = 3;alert(typeof value); // number
// Semicolon insertionreturn{ javascript : "Fantastic!"};
// Semicolon insertionreturn; // Semicolon insertion{ // Considered an empty block javascript : "Fantastic!"}; // Semicolon insertion, dummy line
type of NaN // "number"
3.toString(); // Error3..toString(); // "3"
var number = 5, check = { number: 10, getNum: function () { var number = 20; setTimeout(function () { alert(this.number); }, 10); } };check.getNum(); // 5
http://chrome.angrybirds.com/
Robert Nymanhttp://robertnyman.com/speaking/
Twitter: @robertnyman
Pictures:
Chocolate: http://10000likes.blogspot.com/2010_11_01_archive.htmlRobocop: http://www.meh.ro/2010/04/01/murphy-as-robocop/Bruce Willis: http://www.starsjournal.com/3192/bruce-willis-is-being-sued-for-4-million-dollars.htmlSwedish flag: http://scrapetv.com/News/News%20Pages/usa/Images/swedish-flag.jpgVerona flag: http://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Flag_of_Verona.svg/568px-Flag_of_Verona.svg.pngSwedish woman/flag: http://www.olssonfoto.se/JAlbum/SGP%202008%20Ullevi/slides/Svenska%20flaggan.htmlEuro Coin: http://accidentaldong.blogspot.com/2009/10/euro-uh-oh.htmlMost popular language: http://odetocode.com/Blogs/scott/archive/2009/03/18/signs-that-your-javascript-skills-need-updating.aspxSunrise: http://www.manywallpapers.com/space-wallpapers/earth/sunrise-from-space.htmlAstronaut: http://martianchronicles.wordpress.com/2009/01/23/carnival-of-space-87/Netscape 2: http://blog.explorelearning.com/2005/12/index.htmlInternet Explorer 3: http://www.guidebookgallery.org/screenshots/browserGandalf: http://web.mit.edu/kayla/Public/Backgrounds/LOTR%20Gandalf%204.JPGNow: http://www.chronicbabe.com/articles/801/Axe: http://bestgamewallpapers.com/a3-the-age-of-sovereign/axeMoney: http://logisticsmonster.com/2010/01/12/the-fed-earns-record-profit-loaning-our-money-to-us/joker-burning-money-in-tdk-3/Happy: http://www.petetheplanner.com/blog/2011/03/08/the-cat-poo-story/Fast: http://www.curing-premature-ejaculation.com/Forrest Gump: http://wallpaper-s.org/36__Forrest_Gump,_1994,_Tom_Hanks,_Robin_Wright_Penn.htm
Seinfeld: http://www.cartoonstock.com/directory/f/false_identity.aspForcing: http://www.pollsb.com/polls/p2116218-forcing_guy_look_computer_screenPlay with yourself: http://verydemotivational.memebase.com/2008/06/07/funny-demotivational-posters-masturbation/Overloading: http://theshadowhive.blogspot.com/2010/04/mutating-chaos-gene.htmlDavid Hasselhof: http://www.wimereuxwobblers.co.uk/?page_id=6Pamela Anderson: http://www.dailyheadlineblog.com/television/pamela-andersons-red-swimsuit-up-for-auction/Inheritance: http://www.uniquities.co.uk/acatalog/Get_your_GEEK_on.htmlExtensible (dachshund): http://dog-breeds.findthebest.com/compare/16-55/Beagle-vs-DachshundTiger Woods: http://blogs.bigadda.com/pal4868546/2010/01/Pollution: http://www.fishingfury.com/tags/pollution/Closure: http://today.msnbc.msn.com/id/4760120Steve Ballmer: http://www.businessinsider.com/microsoft-completely-rebooted-its-mobile-strategy-yesterday-heres-what-you-missed-2010-2Crockford: http://gemsres.com/story/nov07/468365/Crockford_New_4681.jpgName: http://blog.usa.gov/roller/govgab/tags/namesSpace: http://gucken.deviantart.com/art/Sunrise-in-Space-56420137Fail better: http://ozguralaz.posterous.com/ever-tried-ever-failed-no-mattHoist: http://www.gantry-crane.org/category/hoist/Mila & Macaulay: http://uk.eonline.com/uberblog/b61889_mila_macaulay_home_alone.htmlLove: http://hyderabadaseels.webs.com/