SlideShare a Scribd company logo
1 of 14
Closure in JavaScript
               By Nicholas Ren,
ThoughtWorks
JavaScript
 The world’s most misunderstood programing language
   looks like an ordinary procedural language.

   has more common with functional language.
    closure, functions are first class.
Closure
 What is it?
 How to create a closure?
 What’s its usage?
 Advantage and disadvantage
What’s a closure?
 closure is a function together with a referencing environment
  for the non-local variables of that function

 closure is a specified kind of object that combines two things:
  a function, and the environment in which that function was
  created

 a function remembers what happens around it
How to create a closure?
 crate a inner function and return it to outside.
 sample:
     function makeAdder(x)
     {
        return function(y)
        {
          return x + y
        }
      }

     var add5 = makeAdder(5);
     var add1000 = makeAdder(1000);

     alert("add5(10)): " + add5(10));
     alert("add1000(10)): " + add1000(10));
Usages of closure
 handle event driven function
 emulate private method
Sample:
handle event driven functions
HTML:
<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
Sample:
handle event driven functions
javascript:
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
 var helpText = [
    {'id': 'email', 'help': 'Your e-mail address'},
    {'id': 'name', 'help': 'Your full name'},
    {'id': 'age', 'help': 'Your age (you must be over 16)'}
  ];

    for (var i = 0; i < helpText.length; i++) {
      var item = helpText[i];
      document.getElementById(item.id).onfocus = function() {
        showHelp(item.help);
      }
    }
}

setupHelp();
Sample:
handle event driven functions
javascript:
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function makeHelpCallback(help) {
  return function() {
    showHelp(help);
  };
}

function setupHelp() {
 var helpText = [
    {'id': 'email', 'help': 'Your e-mail address'},
    {'id': 'name', 'help': 'Your full name'},
    {'id': 'age', 'help': 'Your age (you must be over 16)'}
  ];

    for (var i = 0; i < helpText.length; i++) {
      var item = helpText[i];
      document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
    }
}

setupHelp();
Sample:
emulate private function
Person = function(){
   name = "Adam";
    return {
          getName:function getName(){ return name;},
          setName:function setName(new_name){
                     name = new_name;
                   }
         }
 }
p = new Person();
p.setName("Jim");
alert(p.getName());
Advantage & Disadvantage
 Advantage
   bring any object along with the scope chain
    data encapsulation
    make event handling logic more clear



 Disadvantage:
   slow speed
   more memory consumption
Theory and implementation
 Closures are typically implemented with a special data
  structure that contains a pointer to the function code, plus a
  representation of the function's lexical environment (e.g., the
  set of available variables and their values) at the time when
  the closure was created.

 difficult to implement for a stack based programing language
  because of Funarg problem
Related Terms
 function object
 lamda lifting
 first-class function
 high-order function
Appendix
 http://javascript.crockford.com/javascript.html
 http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexic
  al_scoping
 http://en.wikipedia.org/wiki/Closure_(computer_science)

More Related Content

What's hot

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 

What's hot (20)

Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Php functions
Php functionsPhp functions
Php functions
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
1. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES61. Arrow Functions | JavaScript | ES6
1. Arrow Functions | JavaScript | ES6
 
Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Clean Code
Clean CodeClean Code
Clean Code
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Hibernate
Hibernate Hibernate
Hibernate
 
Closures in Javascript
Closures in JavascriptClosures in Javascript
Closures in Javascript
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Context API in React
Context API in ReactContext API in React
Context API in React
 

Viewers also liked

Wow! closure in_javascript
Wow! closure in_javascriptWow! closure in_javascript
Wow! closure in_javascript
cnlangzi
 

Viewers also liked (11)

rest without put
rest without putrest without put
rest without put
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Wow! closure in_javascript
Wow! closure in_javascriptWow! closure in_javascript
Wow! closure in_javascript
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
 
JavaScript closures
JavaScript closuresJavaScript closures
JavaScript closures
 
Ambient Media Worldwide Ltd Jd Lr
Ambient Media Worldwide Ltd Jd LrAmbient Media Worldwide Ltd Jd Lr
Ambient Media Worldwide Ltd Jd Lr
 
JavaScript closures
JavaScript closuresJavaScript closures
JavaScript closures
 
Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
JavaScript tips - Unnest callbacks and method declarations
JavaScript tips - Unnest callbacks and method declarationsJavaScript tips - Unnest callbacks and method declarations
JavaScript tips - Unnest callbacks and method declarations
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
 

Similar to Closure

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Zohar Arad
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 

Similar to Closure (20)

eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
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.
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 

Recently uploaded

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Recently uploaded (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

Closure

  • 1. Closure in JavaScript By Nicholas Ren, ThoughtWorks
  • 2. JavaScript  The world’s most misunderstood programing language  looks like an ordinary procedural language.  has more common with functional language.  closure, functions are first class.
  • 3. Closure  What is it?  How to create a closure?  What’s its usage?  Advantage and disadvantage
  • 4. What’s a closure?  closure is a function together with a referencing environment for the non-local variables of that function  closure is a specified kind of object that combines two things: a function, and the environment in which that function was created  a function remembers what happens around it
  • 5. How to create a closure?  crate a inner function and return it to outside.  sample: function makeAdder(x) { return function(y) { return x + y } } var add5 = makeAdder(5); var add1000 = makeAdder(1000); alert("add5(10)): " + add5(10)); alert("add1000(10)): " + add1000(10));
  • 6. Usages of closure  handle event driven function  emulate private method
  • 7. Sample: handle event driven functions HTML: <p id="help">Helpful notes will appear here</p> <p>E-mail: <input type="text" id="email" name="email"></p> <p>Name: <input type="text" id="name" name="name"></p> <p>Age: <input type="text" id="age" name="age"></p>
  • 8. Sample: handle event driven functions javascript: function showHelp(help) { document.getElementById('help').innerHTML = help; } function setupHelp() { var helpText = [ {'id': 'email', 'help': 'Your e-mail address'}, {'id': 'name', 'help': 'Your full name'}, {'id': 'age', 'help': 'Your age (you must be over 16)'} ]; for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; document.getElementById(item.id).onfocus = function() { showHelp(item.help); } } } setupHelp();
  • 9. Sample: handle event driven functions javascript: function showHelp(help) { document.getElementById('help').innerHTML = help; } function makeHelpCallback(help) { return function() { showHelp(help); }; } function setupHelp() { var helpText = [ {'id': 'email', 'help': 'Your e-mail address'}, {'id': 'name', 'help': 'Your full name'}, {'id': 'age', 'help': 'Your age (you must be over 16)'} ]; for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; document.getElementById(item.id).onfocus = makeHelpCallback(item.help); } } setupHelp();
  • 10. Sample: emulate private function Person = function(){ name = "Adam"; return { getName:function getName(){ return name;}, setName:function setName(new_name){ name = new_name; } } } p = new Person(); p.setName("Jim"); alert(p.getName());
  • 11. Advantage & Disadvantage  Advantage  bring any object along with the scope chain  data encapsulation  make event handling logic more clear  Disadvantage:  slow speed  more memory consumption
  • 12. Theory and implementation  Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (e.g., the set of available variables and their values) at the time when the closure was created.  difficult to implement for a stack based programing language because of Funarg problem
  • 13. Related Terms  function object  lamda lifting  first-class function  high-order function

Editor's Notes

  1. the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structuresHigh-order functions: functions which do at least one of the following: take one or more functions as an input output a functionwill be consider as a high order functionlexically scope is a property of the program text and is made independent of the runtime call stack by the language implementation.Dynamic scopeWith dynamic scope, each identifier has a global stack of bindings. Introducing a local variable with name x pushes a binding onto the global x stack (which may have been empty), which is popped off when the control flow leaves the scope. Evaluating x in any context always yields the top binding.
  2. Functions in JavaScript are lexically rather than dynamically scoped. This means that they run in the scope in which they are defined, not the scope from which they are executed. When a function is defined, the current scope chain is saved and becomes part of the internal state of the function.
  3. a non-local variable is a variable that is not defined in the local scope
  4. Funarg problem : if the body of a nested function refers directly to identifiers defined in the environment in which the function is defined, but not in the environment of the function call.[