closures

来源:互联网 发布:网络文明有哪些 编辑:程序博客网 时间:2024/06/15 12:09

Closures are functions that have access to variables from another function's scope. This is often accomplished by creating a function inside a function:

function createComparisonFunction(propertyName) {return function (obj1,obj2) {var value1=obj1[propertyName];var value2=obj2[propertyName];if(value1<value2){return -1;}else if(value1>value2){return 1;}else {return 0;}}}

The highlighted lines in this example are part of the inner function ( an anonymous function) that is accessing variable ( propertyName ) from the outer function. Even after the inner function has been returned and is being used elsewhere, it has access to that variable. This occurs because the inner function's scope chain includes the scope of createComparisonFunction(). 


The details of how scope chains are created and used are important for a good understanding of closures. When a function is called, an execution context is created , and its scope chain is created. The activation object for the function is initialized with values for arguments and any named arguments. The outer function's activation object is the second object in the scope chain. This process continues for all containing functions until the scope chain terminates with the global execution context.


Whenever a variable is accessed inside a function, the scope chain is search for a variable with the given name. Once the function has completed, the local activation object is destroyed, leaving only the global scope in memory. Closures , however , behave differently.


A function that is defined inside another function adds the containing  function's activation object into its scope chain.

let compare=createComparisonFunction("name");let result=compare({name:"ni"},{name:"gre"});

When the anonymous function is returned from createComparisonFunction(), its scope chain has been initialized to contain the activation object from createComparisonFunction() and the global variable object. This gives the anonymous function access to all of the variable from createComparisonFunction(). Another interesting side effect is that the activation object from createComparisonFunction() can not be destroyed once the function finishes executing , because a reference still exist in the anonymous function's scope chain.

//create functionlet compare=createComparisonFunction("name");//call functonlet result=compare({name:"ni"},{name:"gre"});//dereference function - memory can now be reclaimedcompare=null;