SlideShare ist ein Scribd-Unternehmen logo
1 von 40
ALL OF JAVASCRIPT
George Mauer
RATE ME ON SPEAKERRATE
http://tinyurl.com/0811-brdnug
 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
12:00 PM CST Thursdays on Livemeeting
www.virtualbrownbag.com
Twitter: @virtualbrownbag
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
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
In the browser Javascript interacts with the
Document Object Model
Browser’s interpretation of HTML
I wanna…use it?
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(…)
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
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
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?");
}
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
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
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)
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
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…
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
Concept #4 – Closures
 Self-executing
functions solve
global scope
issue
var someFunc = function() {
//stuff
}
someFunc();
(function() {
//stuff
})
 Shorten to
Public? Private? Static?
We got you
Concept #4 – Closures
Lots of variations on this module pattern
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
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
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!
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!
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
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!
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
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)
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
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
That Web 2.0 thing? Yeah, that.
Let’s talk about AJAX
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
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…
})();
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!
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");
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
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
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!
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);
}
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
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)

Weitere ähnliche Inhalte

Was ist angesagt?

Unobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQueryUnobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQuerySimon Willison
 
Everything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is WrongEverything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is WrongTim Boudreau
 
Simply - OOP - Simply
Simply - OOP - SimplySimply - OOP - Simply
Simply - OOP - SimplyThomas Bahn
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Glenn Vanderburg — Learning to love JavaScript
Glenn Vanderburg — Learning to love JavaScriptGlenn Vanderburg — Learning to love JavaScript
Glenn Vanderburg — Learning to love JavaScriptatr2006
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...Burt Beckwith
 
Grails Worst Practices
Grails Worst PracticesGrails Worst Practices
Grails Worst PracticesBurt Beckwith
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2kaven yan
 
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...BookNet Canada
 
Validating big data jobs - Spark AI Summit EU
Validating big data jobs  - Spark AI Summit EUValidating big data jobs  - Spark AI Summit EU
Validating big data jobs - Spark AI Summit EUHolden Karau
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patternsPascal Larocque
 

Was ist angesagt? (20)

Unobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQueryUnobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQuery
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Everything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is WrongEverything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is Wrong
 
Simply - OOP - Simply
Simply - OOP - SimplySimply - OOP - Simply
Simply - OOP - Simply
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Glenn Vanderburg — Learning to love JavaScript
Glenn Vanderburg — Learning to love JavaScriptGlenn Vanderburg — Learning to love JavaScript
Glenn Vanderburg — Learning to love JavaScript
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 
Grails Worst Practices
Grails Worst PracticesGrails Worst Practices
Grails Worst Practices
 
Java script unleashed
Java script unleashedJava script unleashed
Java script unleashed
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Git Makes Me Angry Inside
Git Makes Me Angry InsideGit Makes Me Angry Inside
Git Makes Me Angry Inside
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2
 
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...
JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraf...
 
Validating big data jobs - Spark AI Summit EU
Validating big data jobs  - Spark AI Summit EUValidating big data jobs  - Spark AI Summit EU
Validating big data jobs - Spark AI Summit EU
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Pyramid faq
Pyramid faqPyramid faq
Pyramid faq
 

Ähnlich wie All of Javascript

JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4alexsaves
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
Leveling Up at JavaScript
Leveling Up at JavaScriptLeveling Up at JavaScript
Leveling Up at JavaScriptRaymond Camden
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
10 Years of JavaScript
10 Years of JavaScript10 Years of JavaScript
10 Years of JavaScriptMike de Boer
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
The Mysteries Of JavaScript-Fu (@media SF Edition)
The Mysteries Of JavaScript-Fu (@media SF Edition)The Mysteries Of JavaScript-Fu (@media SF Edition)
The Mysteries Of JavaScript-Fu (@media SF Edition)danwrong
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsAjax Experience 2009
 
Real World Single Page App - A Knockout Case Study
Real World Single Page App - A Knockout Case StudyReal World Single Page App - A Knockout Case Study
Real World Single Page App - A Knockout Case Studyhousecor
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaMatteo Baglini
 
The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)danwrong
 

Ähnlich wie All of Javascript (20)

JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Leveling Up at JavaScript
Leveling Up at JavaScriptLeveling Up at JavaScript
Leveling Up at JavaScript
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Web Development with Smalltalk
Web Development with SmalltalkWeb Development with Smalltalk
Web Development with Smalltalk
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
10 Years of JavaScript
10 Years of JavaScript10 Years of JavaScript
10 Years of JavaScript
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
The Mysteries Of JavaScript-Fu (@media SF Edition)
The Mysteries Of JavaScript-Fu (@media SF Edition)The Mysteries Of JavaScript-Fu (@media SF Edition)
The Mysteries Of JavaScript-Fu (@media SF Edition)
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Real World Single Page App - A Knockout Case Study
Real World Single Page App - A Knockout Case StudyReal World Single Page App - A Knockout Case Study
Real World Single Page App - A Knockout Case Study
 
Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)
 

Kürzlich hochgeladen

Gurgaon Call Girls : ☎ 8527673949, Low rate Call Girls
Gurgaon Call Girls : ☎ 8527673949, Low rate Call GirlsGurgaon Call Girls : ☎ 8527673949, Low rate Call Girls
Gurgaon Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
A Selection of Tim Walsh's Recent Paintings
A Selection of Tim Walsh's  Recent PaintingsA Selection of Tim Walsh's  Recent Paintings
A Selection of Tim Walsh's Recent PaintingsTim Walsh
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Servicedoor45step
 
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Delivery
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home DeliveryCall Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Delivery
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Deliverydoor45step
 
Khanpur Call Girls : ☎ 8527673949, Low rate Call Girls
Khanpur Call Girls : ☎ 8527673949, Low rate Call GirlsKhanpur Call Girls : ☎ 8527673949, Low rate Call Girls
Khanpur Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Servicedoor45step
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxLauraFagan6
 
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girls
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call GirlsIffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girls
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Zagor VČ OP 055 - Oluja nad Haitijem.pdf
Zagor VČ OP 055 - Oluja nad Haitijem.pdfZagor VČ OP 055 - Oluja nad Haitijem.pdf
Zagor VČ OP 055 - Oluja nad Haitijem.pdfStripovizijacom
 
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Servicedoor45step
 
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girls
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call GirlsDilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girls
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...door45step
 
Govindpuri Call Girls : ☎ 8527673949, Low rate Call Girls
Govindpuri Call Girls : ☎ 8527673949, Low rate Call GirlsGovindpuri Call Girls : ☎ 8527673949, Low rate Call Girls
Govindpuri Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 60009654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000Sapana Sha
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiMalviyaNagarCallGirl
 
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girls
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call GirlsLaxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girls
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call GirlsKarol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiFULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiMalviyaNagarCallGirl
 
Subway Stand OFF storyboard by Raquel Acosta
Subway Stand OFF storyboard by Raquel AcostaSubway Stand OFF storyboard by Raquel Acosta
Subway Stand OFF storyboard by Raquel Acostaracosta58
 
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call Girl
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call GirlDxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call Girl
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call GirlYinisingh
 

Kürzlich hochgeladen (20)

Gurgaon Call Girls : ☎ 8527673949, Low rate Call Girls
Gurgaon Call Girls : ☎ 8527673949, Low rate Call GirlsGurgaon Call Girls : ☎ 8527673949, Low rate Call Girls
Gurgaon Call Girls : ☎ 8527673949, Low rate Call Girls
 
A Selection of Tim Walsh's Recent Paintings
A Selection of Tim Walsh's  Recent PaintingsA Selection of Tim Walsh's  Recent Paintings
A Selection of Tim Walsh's Recent Paintings
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
 
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Delivery
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home DeliveryCall Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Delivery
Call Girls In Lajpat Nagar 8375860717 Escorts Service Free Home Delivery
 
Khanpur Call Girls : ☎ 8527673949, Low rate Call Girls
Khanpur Call Girls : ☎ 8527673949, Low rate Call GirlsKhanpur Call Girls : ☎ 8527673949, Low rate Call Girls
Khanpur Call Girls : ☎ 8527673949, Low rate Call Girls
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptx
 
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girls
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call GirlsIffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girls
Iffco Chowk Call Girls : ☎ 8527673949, Low rate Call Girls
 
Zagor VČ OP 055 - Oluja nad Haitijem.pdf
Zagor VČ OP 055 - Oluja nad Haitijem.pdfZagor VČ OP 055 - Oluja nad Haitijem.pdf
Zagor VČ OP 055 - Oluja nad Haitijem.pdf
 
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
 
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girls
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call GirlsDilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girls
Dilshad Garden Call Girls : ☎ 8527673949, Low rate Call Girls
 
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...
TOP BEST Call Girls In SECTOR 62 (Noida) ꧁❤ 8375860717 ❤꧂ Female Escorts Serv...
 
Govindpuri Call Girls : ☎ 8527673949, Low rate Call Girls
Govindpuri Call Girls : ☎ 8527673949, Low rate Call GirlsGovindpuri Call Girls : ☎ 8527673949, Low rate Call Girls
Govindpuri Call Girls : ☎ 8527673949, Low rate Call Girls
 
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 60009654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
 
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girls
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call GirlsLaxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girls
Laxmi Nagar Call Girls : ☎ 8527673949, Low rate Call Girls
 
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call GirlsKarol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
 
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiFULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
 
Subway Stand OFF storyboard by Raquel Acosta
Subway Stand OFF storyboard by Raquel AcostaSubway Stand OFF storyboard by Raquel Acosta
Subway Stand OFF storyboard by Raquel Acosta
 
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call Girl
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call GirlDxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call Girl
Dxb Call Girl +971509430017 Indian Call Girl in Dxb By Dubai Call Girl
 

All of Javascript

  • 1. ALL OF JAVASCRIPT George Mauer RATE ME ON SPEAKERRATE http://tinyurl.com/0811-brdnug
  • 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
  • 18. Public? Private? Static? We got you Concept #4 – Closures Lots of variations on this module pattern
  • 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)