S1: Closure

Source: Internet
Author: User

A closure is a function that has the right to access variables in another function scope. A common way to create a closure is to create another function within a function. Take the createcomparisonfunction () function as an example.

function createComparisonFunction(propertyName) {    return function(object1, object2){        var value1 = object1[propertyName];        var value2 = object2[propertyName];        if (value1 < value2){            return -1;        } else if (value1 > value2){            return 1;        } else {            return 0;        }    };}    
// Create the function var comparenames = createcomparisonfunction ("name"); // call the function var result = comparenames ({name: "Nicolas" },{ name: "Greg "}); // unreference anonymous functions (to release memory) comparenames = NULL;

First, the created comparison function is saved in the variable comparenames. By setting comparenames to null to remove the reference of this function, it is equivalent to notifying the garbage collection routine to clear it. As the scope chain of anonymous functions is destroyed, other scopes (except the global scope) can also be safely destroyed. The figure shows the relationship between the scope chains generated when comparenames () is called.

Closure and variable
This configuration mechanism of the scope chain leads to a noteworthy side effect, that is, the closure can only obtain the last value of any variable in the function. Don't forget that the closure stores the entire variable object, not a special variable. The following example clearly illustrates this problem.

function createFunctions(){    var result = new Array();    for (var i=0; i < 10; i++){        result[i] = function(){        return i;        };    }return result;}

On the surface, it seems that every function should return its own index value, that is, the function at the position 0 returns 0, the function at the position 1 returns 1, and so on. But in fact, every function returns 10. Because the scope chain of each function stores the activity objects of the createfunctions () function, they reference the same variable I. When the createfunctions () function returns, the value of variable I is 10. At this time, each function references the same variable that saves variable I.
So the value of I in each function is 10. However, we can create another anonymous function to force the closure to behave as expected, as shown below:

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

Because function parameters are passed by value, the current value of variable I is copied to the parameter num. In this anonymous function. In this way, each function in the result array has a copy of its own num variable, so different values can be returned.

S1: Closure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.