SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1Robert Pearce
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分bob_is_strange
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHPWim Godden
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
JavaScript 1 for high school
JavaScript 1 for high schoolJavaScript 1 for high school
JavaScript 1 for high schooljekkilekki
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScriptKrisKowal2
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Javascript fundamentals for php developers
Javascript fundamentals for php developersJavascript fundamentals for php developers
Javascript fundamentals for php developersChris Ramakers
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming PrimerMike Wilcox
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 

Mais procurados (20)

A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
 
Slide
SlideSlide
Slide
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
JavaScript 1 for high school
JavaScript 1 for high schoolJavaScript 1 for high school
JavaScript 1 for high school
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Lazy Data Using Perl
Lazy Data Using PerlLazy Data Using Perl
Lazy Data Using Perl
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
 
Javascript fundamentals for php developers
Javascript fundamentals for php developersJavascript fundamentals for php developers
Javascript fundamentals for php developers
 
Ruby Internals
Ruby InternalsRuby Internals
Ruby Internals
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 

Destaque

Publisko institūciju rīcībspēja publisko pakalpojumu jomā
Publisko institūciju rīcībspēja publisko pakalpojumu jomāPublisko institūciju rīcībspēja publisko pakalpojumu jomā
Publisko institūciju rīcībspēja publisko pakalpojumu jomānacionalaidentitate
 
MILL, Miller Energy Oil and Gas Investor Article One on One
MILL, Miller Energy Oil and Gas Investor Article One on OneMILL, Miller Energy Oil and Gas Investor Article One on One
MILL, Miller Energy Oil and Gas Investor Article One on OneDerek Gradwell
 
Nacionālā identitāte un tās dimensijas
Nacionālā identitāte un tās dimensijasNacionālā identitāte un tās dimensijas
Nacionālā identitāte un tās dimensijasnacionalaidentitate
 
Garde-corps (FR)
Garde-corps (FR)Garde-corps (FR)
Garde-corps (FR)XSPlatforms
 
AXPLF Arabella Exploration Investor Presentation
AXPLF Arabella Exploration Investor PresentationAXPLF Arabella Exploration Investor Presentation
AXPLF Arabella Exploration Investor PresentationDerek Gradwell
 

Destaque (6)

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

Semelhante a JavaScript Closures and Prototypes Explained

The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascriptRobbin Zhao
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAbimbola Idowu
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginConverting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginthehoagie
 

Semelhante a JavaScript Closures and Prototypes Explained (20)

The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Javascript
JavascriptJavascript
Javascript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
oojs
oojsoojs
oojs
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery pluginConverting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
 

Último

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Último (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

JavaScript Closures and Prototypes Explained

  • 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