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