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)

Closure

  • 1.
    Closure in JavaScript By Nicholas Ren, ThoughtWorks
  • 2.
    JavaScript  The world’smost misunderstood programing language  looks like an ordinary procedural language.  has more common with functional language.  closure, functions are first class.
  • 3.
    Closure  What isit?  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 createa 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 drivenfunctions 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 drivenfunctions 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 drivenfunctions 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  functionobject  lamda lifting  first-class function  high-order function
  • 14.

Editor's Notes

  • #3 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.
  • #4 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.
  • #5 a non-local variable is a variable that is not defined in the local scope
  • #13 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.[