JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.
Upcoming SlideShare
Loading in...5
×
 

JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.

on

  • 1,530 views

Summary of Morris Johns' blog article

Summary of Morris Johns' blog article
and My practical examples.

Statistics

Views

Total Views
1,530
Views on SlideShare
1,530
Embed Views
0

Actions

Likes
1
Downloads
15
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

JavaScript Closures for Dummies & JavaScript prototype, closures and OOP. JavaScript Closures for Dummies & JavaScript prototype, closures and OOP. Presentation Transcript

  • JavaScript Closures forDummiesby Morris Johnshttp://blog.morrisjohns.com/javascript_closures_for_dummies
  • scopeVariables have each function scopes.not in any functions, global variable
  • closuresa closure is a stack-frame which is not dealloctatedwhen the funtion returns. (as if a stack-framewere malloced instead of being on the stack!)In JavaScript, if you use the function keywordinside another function, you are creating a closure.as soon as there are no more references to thefunction that is using the closure, the function/closures should be garbage collected.
  • comparativeC pointer- a pointer to a functionJavaScript reference- a pointer to a function &a hidden pointer to a closure
  • example 3function say667(){// Local variable that ends up within closurevar num = 666;var sayAlert = function() { alert(num); }num++;return sayAlert;}This example shows that the local variables are not copied - theyare kept by reference. It is kind of like keeping a stack-frame inmemory when the outer function exits
  • example 4function setupSomeGlobals(){ // Local variable that ends up within closure var num = 666; // Store some references to functions as global variables gAlertNumber = function() { alert(num); } gIncreaseNumber = function() { num++; } gSetNumber = function(x) { num = x; }}All three global functions have a common reference to the sameclosure because they are all declared within a single call tosetupSomeGlobals().
  • JavaScriptprototype, closures and OOPby Jin Hwa Kim
  • McDuckDuckoverviewBird
  • var Bird = function() { // constructor var kind = "bird"; this.setKind = function(k){ kind = k; }; this.getKind = function(){ return kind; }; this.fly = function(){ console.log( kind + " do fly." ); }; this.sing = function(){ console.log( "lalala." ); };}var angrybird = new Bird();console.log( angrybird.kind ); // undefinedconsole.log( angrybird.getKind() ); // birdangrybird.fly(); // bird do fly.angrybird.sing(); // lalala.
  • inheritanceIn prototype-based programming, objects can be defineddirectly from other objects without the need to define anyclasses, in which case this feature is called differentialinheritance.Differential Inheritance is a common inheritance model used byprototype-based programming languages such as JavaScript, Ioand NewtonScript. It operates on the principle that most objectsare derived from other, more general objects, and only differ in afew small aspects; while usually maintaining a list of pointersinternally to other objects which the object differs from.from wikipedia
  • // Definition of constructorvar Duck = function() { var kind = "duck"; this.shape = "beige feathered duck"; this.describe = function(){ console.log( this.shape ) }; // Overriding, surely. this.fly = function(){ console.log( kind + " cant fly." ); };};Duck.prototype = Bird; // not workedDuck.prototype = new Bird();var dornald = new Duck();dornald.describe(); // beige feathered duckdornald.fly(); // duck cant fly.dornald.sing(); // lalala.
  • var McDuck = function() { var kind = "McDuck"; var steal = function(){ console.log( "steal the money." ); }; this.shape = "white feathered duck"; this.tax = function(){ steal(); console.log( "pay the tax." ); };};McDuck.prototype = new Duck();var scrooge = new McDuck();console.log( scrooge.shape ); // white feathered duckconsole.log( scrooge.kind ); // undefinedconsole.log( scrooge.getKind() ); // birdconsole.log( typeof scrooge.steal ); // undefinedscrooge.describe(); // white feathered duckscrooge.tax(); // steal the money.n pay the tax.
  • // Polymorphismvar birds = [ angrybird, dornald, scrooge ];for( var i in birds ){ birds[i].fly(); // bird do fly.n duck cant fly.n duck cant fly.}
  • var sum = 0;function add_t() { var sum = sum + 20;}add_t();alert( ++sum );
  • use case 1Prototypes bind() function or Dojos dojo.lang.hitch() functionuse closures.Inside the function the this keyword becomes a reference tothat scope. The same function can behave differentlydepending on its execution scopre.Prototype can guarantee that your function will execute withthe object you want under the this keyword just by invokingbind on it.from Prototype JavaScript framework: Function.bind(http://www.prototypejs.org/api/function/bind)
  • use case 2LCMCalculator.prototype = { ...gcd: function () {var a = Math.abs(this.a), b = Math.abs(this.b), t;if (a < b) { t = b; b = a; a = t; }while (b !== 0) { t = b; b = a % b; a = t; }this[gcd] = function() { return a; };return a;} ... };Only need to calculate GCD once, so "redefine" this method. (Actuallynot redefinition - its defined on the instance itself, so that this.gcdrefers to this "redefinition" instead of LCMCalculator.prototype.gcd.)from wikipedia