provides context • this, arguments lørdag den 26. maj 12 Create functions at runtime, decorate functions with properties and even more functions’ Roll them up and pass them around
// object (function anon( context ){ console.log( typeof this ); // object console.log( typeof arguments ); // object console.log( context == this ); // false }( this )); lørdag den 26. maj 12 Passed in context is different from local this keyword
function that provides context and returns another function. The context will exist for the lifetime of the returned function. The provided context can contain private variables and functions Closures are handy when calling any non-blocking functions, like ajax, timeouts or anything in nodeland.
limit || 2; return function sheepCounter(){ count++; return count > goal; }; } var areWeThereYet = makeSheepCounter(); var noReallyAreWeThereYet = makeSheepCounter( 1 ); areWeThereYet(); // false areWeThereYet(); // false areWeThereYet(); // true noReallyAreWeThereYet(); // false noReallyAreWeThereYet(); // true lørdag den 26. maj 12 Each returned function has it’s own context, and in this it’s own count and limit So, to reiterate, a closure is a function that provides context and returns a new function
// blue console.log( this.color ); // red (function ( global ){ var color = 'green'; this.color = 'yellow'; console.log( color ); // green console.log( this.color ); // yellow console.log( global.color ); // red }( this )); lørdag den 26. maj 12 Function invocation pattern
return this.color; } }; console.log( myObject.getColor() ); // red lørdag den 26. maj 12 Method invocation pattern this refers to the object, and not the executing function
var myCar = new Car( 'black' ); console.log( myCar ); // { color: 'black' } lørdag den 26. maj 12 Constructor invocation pattern this refers to the returned object, not the constructor itself
* 2 ); } }; var mixin = function( target, mixer ){ for ( var p in mixer ){ if ( mixer.hasOwnProperty( p ) && typeof mixer[p] === 'function' ){ target[p] = mixer[p]; } } }; // instance function Thing( val ){ this.value = val || 0; } var myThing = new Thing( 10 ); mixin( myThing, INTEGER_MATH ); console.log( myThing.doubleValue() ); // 20 lørdag den 26. maj 12 Mixin with instance
* 2 ); } }; var mixin = function( target, mixer ){ for ( var p in mixer ){ if ( mixer.hasOwnProperty( p ) && typeof mixer[p] === 'function' ){ target[p] = mixer[p]; } } }; // constructor function Thing( val ){ this.value = val || 0; mixin( this, INTEGER_MATH ); } var myThing = new Thing( Math.PI ); console.log( myThing.doubleValue() ); // 6 lørdag den 26. maj 12 Mixin with constructor
Kittens! lørdag den 26. maj 12 this references current context (or window if function invocation pattern in browser) Closure is a function that provides context and returns a function call / apply allows you to redefine what this is