SlideShare a Scribd company logo
JavaScript Closures for
Dummies
by Morris Johns
http://blog.morrisjohns.com/javascript_closures_for_dummies
scope
Variables have each function scopes.
not in any functions, global variable
closures
a closure is a stack-frame which is not dealloctated
when the funtion returns. (as if a 'stack-frame'
were malloc'ed instead of being on the stack!)
In JavaScript, if you use the function keyword
inside another function, you are creating a closure.
as soon as there are no more references to the
function that is using the closure, the function/
closures should be garbage collected.
comparative
C pointer
- a pointer to a function
JavaScript reference
- a pointer to a function &
a hidden pointer to a closure
example 3
function say667()
{
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
This example shows that the local variables are not copied - they
are kept by reference. It is kind of like keeping a stack-frame in
memory when the outer function exits
example 4
function 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 same
closure because they are all declared within a single call to
setupSomeGlobals().
JavaScript
prototype, closures and OOP
by Jin Hwa Kim
McDuck
Duck
overview
Bird
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 ); // undefined
console.log( angrybird.getKind() ); // bird
angrybird.fly(); // bird do fly.
angrybird.sing(); // lalala.
inheritance
In prototype-based programming, objects can be defined
directly from other objects without the need to define any
classes, in which case this feature is called differential
inheritance.
Differential Inheritance is a common inheritance model used by
prototype-based programming languages such as JavaScript, Io
and NewtonScript. It operates on the principle that most objects
are derived from other, more general objects, and only differ in a
few small aspects; while usually maintaining a list of pointers
internally to other objects which the object differs from.
from wikipedia
// Definition of constructor
var 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 + " can't fly." ); };
};
Duck.prototype = Bird; // not worked
Duck.prototype = new Bird();
var dornald = new Duck();
dornald.describe(); // beige feathered duck
dornald.fly(); // duck can't 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 duck
console.log( scrooge.kind ); // undefined
console.log( scrooge.getKind() ); // bird
console.log( typeof scrooge.steal ); // undefined
scrooge.describe(); // white feathered duck
scrooge.tax(); // steal the money.n pay the tax.
// Polymorphism
var birds = [ angrybird, dornald, scrooge ];
for( var i in birds )
{
	 birds[i].fly(); // bird do fly.n duck can't fly.n duck can't fly.
}
var sum = 0;
function add_t() {
	 var sum = sum + 20;
}
add_t();
alert( ++sum );
use case 1
Prototype's bind() function or Dojo's dojo.lang.hitch() function
use closures.
Inside the function the this keyword becomes a reference to
that scope. The same function can behave differently
depending on its execution scopre.
Prototype can guarantee that your function will execute with
the object you want under the this keyword just by invoking
bind on it.
from Prototype JavaScript framework: Function.bind
(http://www.prototypejs.org/api/function/bind)
use case 2
LCMCalculator.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. (Actually
not redefinition - it's defined on the instance itself, so that this.gcd
refers to this "redefinition" instead of LCMCalculator.prototype.gcd.)
from wikipedia

More Related Content

PDF
Swift で JavaScript 始めませんか? #iOSDC
ODP
HailDB: A NoSQL API Direct to InnoDB
PDF
Fundamental JavaScript [UTC, March 2014]
PPTX
JavaScript Basics and Trends
PDF
Practical JavaScript Programming - Session 6/8
KEY
Writing Ruby Extensions
ZIP
PDF
Back to the Future with TypeScript
Swift で JavaScript 始めませんか? #iOSDC
HailDB: A NoSQL API Direct to InnoDB
Fundamental JavaScript [UTC, March 2014]
JavaScript Basics and Trends
Practical JavaScript Programming - Session 6/8
Writing Ruby Extensions
Back to the Future with TypeScript

What's hot (20)

PDF
A Re-Introduction to JavaScript
PDF
TypeScript Introduction
PDF
JavaScript 101 - Class 1
PDF
PDF
Swiftの関数型っぽい部分
ODP
The promise of asynchronous PHP
PPT
JavaScript Tutorial
ODP
Javascript
PDF
JavaScript Basics and Best Practices - CC FE & UX
PPT
JavaScript Basics
PPTX
JavaScript 1 for high school
PPTX
Hardened JavaScript
PPTX
Type Driven Development with TypeScript
PDF
Lazy Data Using Perl
PDF
JavaScript Primer
PDF
Javascript fundamentals for php developers
KEY
Ruby Internals
PPT
A Deeper look into Javascript Basics
KEY
The JavaScript Programming Primer
PDF
Introduction into ES6 JavaScript.
A Re-Introduction to JavaScript
TypeScript Introduction
JavaScript 101 - Class 1
Swiftの関数型っぽい部分
The promise of asynchronous PHP
JavaScript Tutorial
Javascript
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics
JavaScript 1 for high school
Hardened JavaScript
Type Driven Development with TypeScript
Lazy Data Using Perl
JavaScript Primer
Javascript fundamentals for php developers
Ruby Internals
A Deeper look into Javascript Basics
The JavaScript Programming Primer
Introduction into ES6 JavaScript.
Ad

Viewers also liked (6)

PPT
Darba tirgus reģionos
PPT
Publisko institūciju rīcībspēja publisko pakalpojumu jomā
PDF
MILL, Miller Energy Oil and Gas Investor Article One on One
PDF
Nacionālā identitāte un tās dimensijas
PDF
Garde-corps (FR)
PDF
AXPLF Arabella Exploration Investor Presentation
Darba tirgus reģionos
Publisko institūciju rīcībspēja publisko pakalpojumu jomā
MILL, Miller Energy Oil and Gas Investor Article One on One
Nacionālā identitāte un tās dimensijas
Garde-corps (FR)
AXPLF Arabella Exploration Investor Presentation
Ad

Similar to JavaScript Closures for Dummies & JavaScript prototype, closures and OOP. (20)

PPT
Advanced JavaScript
PDF
Javascript
KEY
Javascript tid-bits
PPT
Java script unleashed
PPTX
Ian 20150116 java script oop
PDF
JavaScript Inheritance
PPT
JavaScript - Programming Languages course
PDF
Prototype
PPTX
Ajaxworld
PPT
JavaScript In Object Oriented Way
PPT
Advanced Javascript
PPT
Advanced Javascript
PPT
Advanced Javascript
PPT
Advanced JavaScript
PDF
JavaScript Core
PPTX
Oojs 1.1
PDF
Prototype 120102020133-phpapp02
PDF
The many facets of code reuse in JavaScript
PDF
Java Script Workshop
Advanced JavaScript
Javascript
Javascript tid-bits
Java script unleashed
Ian 20150116 java script oop
JavaScript Inheritance
JavaScript - Programming Languages course
Prototype
Ajaxworld
JavaScript In Object Oriented Way
Advanced Javascript
Advanced Javascript
Advanced Javascript
Advanced JavaScript
JavaScript Core
Oojs 1.1
Prototype 120102020133-phpapp02
The many facets of code reuse in JavaScript
Java Script Workshop

Recently uploaded (20)

PDF
Advanced IT Governance
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
cuic standard and advanced reporting.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced IT Governance
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Diabetes mellitus diagnosis method based random forest with bat algorithm
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
GamePlan Trading System Review: Professional Trader's Honest Take
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
cuic standard and advanced reporting.pdf
Understanding_Digital_Forensics_Presentation.pptx
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Per capita expenditure prediction using model stacking based on satellite ima...
Dropbox Q2 2025 Financial Results & Investor Presentation
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
20250228 LYD VKU AI Blended-Learning.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing

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

  • 1. JavaScript Closures for Dummies by Morris Johns http://blog.morrisjohns.com/javascript_closures_for_dummies
  • 2. scope Variables have each function scopes. not in any functions, global variable
  • 3. closures a closure is a stack-frame which is not dealloctated when the funtion returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!) In JavaScript, if you use the function keyword inside another function, you are creating a closure. as soon as there are no more references to the function that is using the closure, the function/ closures should be garbage collected.
  • 4. comparative C pointer - a pointer to a function JavaScript reference - a pointer to a function & a hidden pointer to a closure
  • 5. example 3 function say667() { // Local variable that ends up within closure var num = 666; var sayAlert = function() { alert(num); } num++; return sayAlert; } This example shows that the local variables are not copied - they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits
  • 6. example 4 function 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 same closure because they are all declared within a single call to setupSomeGlobals().
  • 9. 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 ); // undefined console.log( angrybird.getKind() ); // bird angrybird.fly(); // bird do fly. angrybird.sing(); // lalala.
  • 10. inheritance In prototype-based programming, objects can be defined directly from other objects without the need to define any classes, in which case this feature is called differential inheritance. Differential Inheritance is a common inheritance model used by prototype-based programming languages such as JavaScript, Io and NewtonScript. It operates on the principle that most objects are derived from other, more general objects, and only differ in a few small aspects; while usually maintaining a list of pointers internally to other objects which the object differs from. from wikipedia
  • 11. // Definition of constructor var 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 + " can't fly." ); }; }; Duck.prototype = Bird; // not worked Duck.prototype = new Bird(); var dornald = new Duck(); dornald.describe(); // beige feathered duck dornald.fly(); // duck can't fly. dornald.sing(); // lalala.
  • 12. 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 duck console.log( scrooge.kind ); // undefined console.log( scrooge.getKind() ); // bird console.log( typeof scrooge.steal ); // undefined scrooge.describe(); // white feathered duck scrooge.tax(); // steal the money.n pay the tax.
  • 13. // Polymorphism var birds = [ angrybird, dornald, scrooge ]; for( var i in birds ) { birds[i].fly(); // bird do fly.n duck can't fly.n duck can't fly. }
  • 14. var sum = 0; function add_t() { var sum = sum + 20; } add_t(); alert( ++sum );
  • 15. use case 1 Prototype's bind() function or Dojo's dojo.lang.hitch() function use closures. Inside the function the this keyword becomes a reference to that scope. The same function can behave differently depending on its execution scopre. Prototype can guarantee that your function will execute with the object you want under the this keyword just by invoking bind on it. from Prototype JavaScript framework: Function.bind (http://www.prototypejs.org/api/function/bind)
  • 16. use case 2 LCMCalculator.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. (Actually not redefinition - it's defined on the instance itself, so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.) from wikipedia