0
All of Javascript<br />George Mauer<br />Rate Me On SpeakerRate<br />http://tinyurl.com/0811-brdnug<br />
Owner of Humble Pi Consulting<br />Current senior developer at Surge<br />Former Senior Software Developer at EPS Software...
Join Us For the Virtual Brown Bag<br />12:00 PM CST Thursdays on Livemeeting<br />www.virtualbrownbag.com<br />Twitter: @v...
Javascript is….<br />Actually called ECMAScript<br />Why Javascript?<br />Most popular language<br />Lightweight conceptua...
I want it!<br />You got it…in your browser<br />Use developer add-ons<br />Chrome (Ctrl+Shift+J)<br />IE (F12)<br />Firefo...
In the browser Javascript interacts with the Document Object Model <br />Browser’s interpretation of HTML<br />I wanna…use...
Your script in the page<br /><script> tag<br />Inline<br />Or Link<br />Another HTTP request is made and the script file i...
Syntax – Javascript is NOT Java<br />No type declaration<br />varsomeInt = 123<br />console.log(someInt)<br />Strings use ...
Control Structures<br />Yes, there are <br />exceptions and try…catch blocks<br />do…while loops<br />if and switch statem...
Concept #1 – Objects as Hashes<br />No such thing as classes, just objects<br />So there’s just anonymous objects<br />Obj...
Concept #1 – Objects as Hashes<br />Objects ARE Hashes/Dictionaries<br />myObject.propertyName == myObject[“propertyName”]...
Functions<br />Use the function keyword<br />No type information on parameters<br />All functions return something (though...
Concept #2 – First Class Functions<br />Functions are objects<br />Can be stored in variables<br />Or parameters to other ...
Function Closures<br />Similar to lambdas in LINQ<br />Great for helper functions<br />It works exactly how you instinctua...
Concept #3 – Loose Typing<br />Really there are types<br />Strings, Integers, floats<br />But you can write whatever you w...
Concept #3 – Loose Typing<br />Loose means coercions on the spot<br />This can get wonky<br />1+2+"3" == "33“<br />"1"+2+3...
Concept #4 – Closures<br />Addresses one of the biggest problems – global scope<br />Functions can be nested inside each o...
Concept #4 – Closures<br />Self-executing functions solve global scope issue<br />varsomeFunc = function() {<br /> //stuff...
Public? Private? Static?We got you<br />Concept #4 – Closures<br />Lots of variations on this module pattern<br />
Concept #5 – Prototypes<br />Javascript is object-oriented and has no classes!<br />Prototype inheritance<br />Simpler – e...
Concept #5 – Prototypes: new<br />Javascript has a ‘new’ keyword<br />Very different from C# new<br />You don’t really nee...
What is JSON?<br />A subset of Javascript for transporting data<br />Functionally equivalent to XML<br />But way more succ...
Cross-Domain Ajax<br />The probleM<br />I go to amazon.com and log in<br />My browser stores information (cookies) to iden...
Same Origin Policy<br />Browsers limit your ability to request resources across domains<br />In general you can request an...
Cross-Domain Solutions<br />Display data from other domains in iframes<br />Cannot use that data<br />Do all queries to ot...
Odds and Ends – Jasmine<br />Testing is even more important in dynamic languages<br />No compiler to catch errors<br />Eas...
Odds and Ends – Coffeescript<br />Lightweight Javascript compiler that removes the suck<br />Gets rid of the function keyw...
Why Libraries?<br />Mismatches in browser implementations<br />The standard DOM interface is awful<br />Internet Explorer ...
Some Resources<br />Douglas Crockford’sJavaScript the Good Parts<br />Video<br />Mozilla Developer Center – by far the bes...
That Web 2.0 thing? Yeah, that.<br />Let’s talk about AJAX<br />
HTTP Model<br />Problems <br />Refresh is ugly<br />Unnecessary bandwith<br />The operation is user triggered<br />Solutio...
The Global Scope<br />You don’t have to use var<br />If you don’t, assignment bubbles up like you would think<br />All the...
More Javascript - Prototypes<br />Javascript is object-oriented and has no classes!<br />Prototype inheritance<br />Simple...
What’s new?<br />Javascript has a ‘new’ keywoad<br />But no traditional inheritance<br />You don’t really need to use ‘new...
What’s this?<br />Javascript has the ‘this’ keyword<br />Use it to refer to the current scope / context<br />Sort of<br />...
Odds and Ends – RegEx<br />Traditionally more important in dynamic languages<br />Two ways to create<br />var r1 = /^a+./;...
Odds and Ends – XSS<br />Cross Site Scripting – someone causes their Javascript to run on your site for other users<br />D...
Javascript Weirdness - Hoisting<br />Variable declarations are moved to the top of the scope<br />Function declarations ar...
Javascript Weirdness<br />for..in loops through all keys on hash / properties on object<br />Including those in the protot...
Javascript Weirdness<br />String Duality<br />Native and object representations of strings<br />typeof comparison won’t al...
Upcoming SlideShare
Loading in...5
×

All of javascript

2,203

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,203
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
35
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "All of javascript"

  1. 1. All of Javascript<br />George Mauer<br />Rate Me On SpeakerRate<br />http://tinyurl.com/0811-brdnug<br />
  2. 2. Owner of Humble Pi Consulting<br />Current senior developer at Surge<br />Former Senior Software Developer at EPS Software<br />Member - VirtualBrownBag, VirtualAltNet, gnocode, PhpNOLA, RubyBayou<br />Improv and sketch Comedy with www.NolaComedy.com<br />http://georgemauer.net/blog<br />@togakangaroo<br />gmauer@gmail.com<br />About Me<br />
  3. 3. Join Us For the Virtual Brown Bag<br />12:00 PM CST Thursdays on Livemeeting<br />www.virtualbrownbag.com<br />Twitter: @virtualbrownbag<br />
  4. 4. Javascript is….<br />Actually called ECMAScript<br />Why Javascript?<br />Most popular language<br />Lightweight conceptually<br />It will make your C# a lot better<br />All the cool kids are doing it<br />
  5. 5. I want it!<br />You got it…in your browser<br />Use developer add-ons<br />Chrome (Ctrl+Shift+J)<br />IE (F12)<br />Firefox<br />Web Development Helper<br />Firebug<br />Enable Console and we’re interactive<br />
  6. 6. In the browser Javascript interacts with the Document Object Model <br />Browser’s interpretation of HTML<br />I wanna…use it?<br />
  7. 7. Your script in the page<br /><script> tag<br />Inline<br />Or Link<br />Another HTTP request is made and the script file is downloaded<br />Cached<br />Order and download timing matters<br />Words!<br />Minification<br />Bundling<br />CDNs<br />Global scope<br />You have to be careful of the source<br />For now let’s use console.log(…)<br />
  8. 8. Syntax – Javascript is NOT Java<br />No type declaration<br />varsomeInt = 123<br />console.log(someInt)<br />Strings use “ or ‘<br />Yes, there are <br />exceptions and try…catch blocks<br />do…while loops<br />if and switch statements<br />No, we will not talk about them<br />Except the for loop<br />There is no function to evaluate strings<br />There is nothing to: eval(“alert(‘javascript!’)”);<br />(There totally is, but shhh…)<br />Semi-colons are optional…ish<br />
  9. 9. Control Structures<br />Yes, there are <br />exceptions and try…catch blocks<br />do…while loops<br />if and switch statements<br />No, we will not talk about them<br />Except the for loop<br />There is no function to <br />varsomeString = “alert(‘javascript!’)”;eval(someString);<br />(There totally is, but shhh…)<br />Semi-colons are optional…ish<br />
  10. 10. Concept #1 – Objects as Hashes<br />No such thing as classes, just objects<br />So there’s just anonymous objects<br />Object Literal:<br />Comma-separated, Colon denoted hash<br />Trailing commas not allowed<br />Nothing is immutable<br />You can add properties<br />Functions too!<br />var person = {<br /> name: "Brian May",<br /> occupation: "Mucisian",<br /> who: function() {<br /> console.log(this.name+": I used to be in Queen")<br /> }<br />};<br />person.phD = "Astronomy";<br />person.playMusic = function() {<br /> console.log("Is this the real life?");<br />}<br />
  11. 11. Concept #1 – Objects as Hashes<br />Objects ARE Hashes/Dictionaries<br />myObject.propertyName == myObject[“propertyName”]<br />Use console.dir() to explore objects<br />Arrays<br />Comma separated, Square brackets<br />Elements in array can be of any type<br />Arrays are objects<br />
  12. 12. Functions<br />Use the function keyword<br />No type information on parameters<br />All functions return something (though it might be undefined)<br />When invoking parameters are always optional<br />Do you care?<br />function youLike(name) {<br /> if(typeof name === 'undefined') {<br />console.error("I don’t know who to like");<br /> return;<br /> }<br /> return 'I like ' + name;<br />}<br />console.log(youLike('fred'))<br /> // I like fred<br />console.log(youLike())// I don’t know who to like<br /> // undefined<br />
  13. 13. Concept #2 – First Class Functions<br />Functions are objects<br />Can be stored in variables<br />Or parameters to other functions<br />Functions can have properties! They are just objects that can be invoked.<br />So how are they not objects?<br />Functions are invokable<br />That’s it (for now)<br />
  14. 14. Function Closures<br />Similar to lambdas in LINQ<br />Great for helper functions<br />It works exactly how you instinctually think it should<br />Nest as many as you want<br />Not visible outside of functions<br />Anonymous functions can be assigned to variables<br />vartellHistory = function () {<br />var who;<br /> function warBrokeOut() {<br /> console.log('war broke out');<br /> console.log('lots of '+who+' died');<br /> }<br /> who = 'Cavemen';<br /> console.log(who+' invented axes');<br />warBrokeOut(); <br /> who = 'Babylonians';<br /> console.log(who+' invented laws');<br />warBrokeOut();<br /> who = 'Greeks';<br /> console.log( who+' invented democracy');<br />warBrokeOut();<br />warBrokeOut();<br />}<br />
  15. 15. Concept #3 – Loose Typing<br />Really there are types<br />Strings, Integers, floats<br />But you can write whatever you want<br />JS has it covered: 99% of the time it just works<br />
  16. 16. Concept #3 – Loose Typing<br />Loose means coercions on the spot<br />This can get wonky<br />1+2+"3" == "33“<br />"1"+2+3 == "33“<br />2==false;<br />=== operator will prevent coercion and is recommend<br />It’s weird but if you know what you’re doing…<br />
  17. 17. Concept #4 – Closures<br />Addresses one of the biggest problems – global scope<br />Functions can be nested inside each other<br />Scope works exactly as you instinctively think it would<br />
  18. 18. Concept #4 – Closures<br />Self-executing functions solve global scope issue<br />varsomeFunc = function() {<br /> //stuff<br />}<br />someFunc();<br />//shorten to<br />(function() {<br /> //stuff<br />})<br />
  19. 19. Public? Private? Static?We got you<br />Concept #4 – Closures<br />Lots of variations on this module pattern<br />
  20. 20. Concept #5 – Prototypes<br />Javascript is object-oriented and has no classes!<br />Prototype inheritance<br />Simpler – each object has a prototype object<br />Flexible – can mimic class inheritance and more<br />Remember: Every object is a hash<br />Plus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)<br />Q: Do you have a cupOfSugar?<br />Yes I do (object has cupOfSugar in the hash)<br />No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])<br />No I don’t (object does not and [[prototype]] is null)<br />Can be used to emulate Class Inheritance<br />Enables duck-typing, class-wide dynamicism, more!<br />I recommend a style where you do not use this often<br />
  21. 21. Concept #5 – Prototypes: new<br />Javascript has a ‘new’ keyword<br />Very different from C# new<br />You don’t really need to use ‘new’ for OO in Javascript<br />What does ‘new do’?<br />All functions have a not null prototype property<br />creates a function with the [[prototype]] set to the constructor function’s prototype property <br />You can enforce ‘new’<br />Anti-intuitively works on functions but not objects<br />Newer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)<br />Constructor functions denoted via convention.<br />Capitalize constructor functions<br />camelCase non-constructor functions<br />
  22. 22. What is JSON?<br />A subset of Javascript for transporting data<br />Functionally equivalent to XML<br />But way more succinct<br />Lingua franca for ajax data-exchange<br />Twitter.com – look at the dev tools network tab<br />JSON is parsed with JSON parser, not eval’ed!<br />
  23. 23. Cross-Domain Ajax<br />The probleM<br />I go to amazon.com and log in<br />My browser stores information (cookies) to identify me to Amazon<br />I then go to evilpage.com<br />Uses ajax to contact amazon.com<br />My browser thinking the amazon session is still on sends my Amazon<br />Amazon sends back secret information to evilpage.com!<br />
  24. 24. Same Origin Policy<br />Browsers limit your ability to request resources across domains<br />In general you can request and use across domains<br />Display images<br />Run scripts<br />Display iframe<br />You cannot have programmatic access to these resources<br />Analyze images from other domains in JS<br />Get arbitrary scripts as a string<br />Inspect cross-domain iframe’s DOM<br />Resources for understanding:<br />Eric Law on the policy<br />Phil Haackon a simple exploit with this<br />
  25. 25. Cross-Domain Solutions<br />Display data from other domains in iframes<br />Cannot use that data<br />Do all queries to other domains server side<br />Can much better control caching<br />Protected better against format changes<br />Takes up your bandwith<br />JSONP<br />Service returns and executes:<br />Cross-domain script execution is ok<br />Assumes you have a global method called myMethod<br />Evaluated, not parsed like JSON<br />Dangerous – if the site is compromised it can inject any script!<br />Always think twice when sending secure data!<br />myMethod({name: ‘George’})<br />
  26. 26. Odds and Ends – Jasmine<br />Testing is even more important in dynamic languages<br />No compiler to catch errors<br />Easy to screw up global state<br />Jasmine is a lightweight testing framework<br />Based on ruby’s rspec<br />Really simple and easy to learn<br />Sample specs from gim.ShannonGame<br />
  27. 27. Odds and Ends – Coffeescript<br />Lightweight Javascript compiler that removes the suck<br />Gets rid of the function keyword<br />Significant whitespace and no need for parens<br />Postfix conditions (number = 42 if answer== true)<br />Splats and object decomposition<br />Comprehensions<br />Easier inheritance setups<br />Try it out<br />Reverse compiler is a great learning tool<br />Heavily influencing the future of Javascript (Harmony)<br />
  28. 28. Why Libraries?<br />Mismatches in browser implementations<br />The standard DOM interface is awful<br />Internet Explorer <8 sucks<br />Unforeseen standards adopted (ie. CSS)<br />Standardize these away<br />jQuery, prototype, mootools, ext-js, yui, others<br />Jsfiddle.net - Try them out<br />
  29. 29. Some Resources<br />Douglas Crockford’sJavaScript the Good Parts<br />Video<br />Mozilla Developer Center – by far the best documentation<br />When searching for javascript help, add on “MDC”<br />Introduction to javascript from MDC<br />Javascript OO<br />Javascript Garden<br />Fascinating Elegant Code beginner series<br />Hidden Features of Javascript on StackOverflow<br />jsfiddle.net – In-browser js prototyping sandbox complete with syntax highlighting, formatting, javascript libraries inclusion, and code pasting for sharing<br />Google Closure – how not to write javascript<br />The console object API<br />JSLint – Douglas Crockford’s syntax checker.<br />Best explanation of the new keyword.<br />Paul Irish Learns from jQuery source, and more<br />jQuery API Reference <br />Rate Me on SpeakerRate: <br />http://tinyurl.com/0811-brdnug<br />www.virtualbrownbag.com<br />
  30. 30.
  31. 31. That Web 2.0 thing? Yeah, that.<br />Let’s talk about AJAX<br />
  32. 32. HTTP Model<br />Problems <br />Refresh is ugly<br />Unnecessary bandwith<br />The operation is user triggered<br />Solution<br />Use javascript to fetch data and update the page when it is returned<br />jQuery has some great helpers for this. Example<br />
  33. 33. The Global Scope<br />You don’t have to use var<br />If you don’t, assignment bubbles up like you would think<br />All the way to the global window object!<br />So always use var<br />Isolate yourself from global scope with self-executing functions<br />Explanation of variables, properties, scopes<br />function doStuff() {<br />varfirstName = 'Fred';<br /> function changeName() {<br />firstName = 'Jim';<br />lastName = 'Halpern';<br /> } <br />changeName();<br />}<br />doStuff();<br />firstName; // undefined<br />lastName; // Halpern – huh?<br />window.lastName; // Halpern – uh oh!<br />(function() {<br /> …doWhatever…<br />})();<br />
  34. 34. More Javascript - Prototypes<br />Javascript is object-oriented and has no classes!<br />Prototype inheritance<br />Simpler – each object has a prototype object<br />Flexible – can mimic class inheritance and more<br />Remember: Every object is a hash<br />Plus a [[prototype]] attribute (revealed in some browsers by the __proto__ property)<br />Q: Do you have a cupOfSugar?<br />Yes I do (object has cupOfSugar in the hash)<br />No I don’t but let me ask Peter (object does not but Peter is the [[prototype]])<br />No I don’t (object does not and [[prototype]] is null)<br />Can be used to emulate Class Inheritance<br />Enables duck-typing, class-wide dynamicism, more!<br />
  35. 35. What’s new?<br />Javascript has a ‘new’ keywoad<br />But no traditional inheritance<br />You don’t really need to use ‘new’ for OO in Javascript<br />What does ‘new do’?<br />All functions have a not null prototype property<br />creates a function with the [[prototype]] set to the constructor function’s prototype property <br />You can enforce ‘new’<br />Anti-intuitively works on functions but not objects<br />Newer versions of Javascript (> 1.8.5) deprecate ‘new’ for Object.create(withPrototype)<br />Constructor functions denoted via convention.<br />Capitalize constructor functions<br />camelCase non-constructor functions<br />function createPerson(name, age) {<br /> return {<br /> name: name,<br /> age: age,<br />toString: function() { return this.name + " is " + this.age + " years old“; }<br /> }<br />}<br />var bob= createPerson("bob", 39);<br />varsal = createPerson("sal", 22);<br />-------------------------------------------------------------<br />var Cat = function(catName) {<br />this.catName = catName;<br />};<br />Cat.prototype.meow = function() {<br /> console.log(this.catName+" says meow");<br />}<br />var mittens = new Cat("Mittens");<br />var whiskers = new Cat("Whiskers");<br />
  36. 36. What’s this?<br />Javascript has the ‘this’ keyword<br />Use it to refer to the current scope / context<br />Sort of<br />Lots of caveats<br />It usually works how you think but double check<br />Can also be substituted with function’s call() or apply() methods<br />Can be useful for method reuse<br />
  37. 37. Odds and Ends – RegEx<br />Traditionally more important in dynamic languages<br />Two ways to create<br />var r1 = /^a+./;<br />var r2 = new RegEx("^a+.");<br />r1.exec(str); // Returns array of matches<br />r1.test(str); // Returns true if there is a match<br />str.match(r1); //Returns an array of Matches<br />str.search(r1); //Returns idx if there is a match or -1<br />str.replace(r1); //Returns string with regex replaced<br />str.split(r1); //Returns an array of substrings<br />
  38. 38. Odds and Ends – XSS<br />Cross Site Scripting – someone causes their Javascript to run on your site for other users<br />Dangerous for: Comments / forums / twitter feeds where you can post things other people can see<br />Search areas or GET urls where long user submissions can be embedded in a link<br />Examples of simple XSS attacks<br />How to prevent it:<br />Ensure all user input reflected back is Html encoded<br />Don’t place anything from GET requests on the page<br />Be aware and think!<br />
  39. 39. Javascript Weirdness - Hoisting<br />Variable declarations are moved to the top of the scope<br />Function declarations are created and declared in the same step<br />At the top of the scope<br />Function assignments are similar to variable declarations<br />Consider declaring all variables in scope with one var statement<br />var bob, joe, jill;<br />var num = 56;<br />function calc() {<br /> console.log(num);<br />var num = 12;<br /> console.log(num);<br />}<br />function calc_isReally() {<br />var num;<br /> console.log(num);<br /> num = 12;<br /> console.log(num);<br />}<br />
  40. 40. Javascript Weirdness<br />for..in loops through all keys on hash / properties on object<br />Including those in the prototype chain which isn’t very helpful<br />Use hasOwnProperty() if this is not desired behavior<br />Don’t use this to enumerate Arrays<br />for loop – similar to for loop in c# or c++<br />Use it to loop through arrays<br />But remember Array.length is a calculated property!<br />for(vari=0; i<arr.length; ++i) { }  Bad!<br />for(vari=0, len=arr.length; i<len; ++i) { }  OK<br />
  41. 41. Javascript Weirdness<br />String Duality<br />Native and object representations of strings<br />typeof comparison won’t always work<br />Do you really need to check type?<br />Really?<br />parseInt(), parseFloat() are not so simple<br />What should parseInt("010") return?<br />Read the MDC docs when using built-in functions (there aren’t that many)<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×