Closures and Variables

Description

The closure always gets the last value of any variable from the containing function.

The closure stores a reference to the entire variable object, not just to a particular variable.

Example

You can force the closures to act appropriately by creating another anonymous function, as follows:


function createFunctions(){//w w w  .j  av a2 s  . c  o m
   var result = new Array();

   for (var i=0; i < 10; i++){
         result[i] = function(num){
             return function(){
                 return num;
             };
         }(i);
   }
   return result;
}
console.log(createFunctions());

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions