Closures in JavaScript

Source: Internet
Author: User

/** * Closure is a professional vocabulary, so as to appear in JS is tall on the goods, the official definition I do not dare to modify it here, * defined as follows: is a function that has access to a variable of another function scope. *//** * 1, closure of the classic example * This is a classic example of closure principle, where is the classic? * When I use compare in the example, my function is accessible to the PropertyName field in the Createcomparison function, but this understanding is not complicated, we have to look at the browser scope variables to be clear. *  *///comparison functions function Createcomparison (propertyname) {return function (Obj1, obj2) {var item1 = Obj1[propertyname];var item2 = obj2[propertyname];if (Item1 < item2) return-1;if (item1 > Item2) return 1;if (item1 = = item2) return 0;}} Compare Namevar compare = Createcomparison ("name"), var result = Compare ({name: "D", age:20}, {name: "C", age:27});

/** * We can see clearly that the local variables list in the current execution function is clearly recorded in the local variable table of chrome, and also categorized, such as "local function variable (local)", "Include function variable (Closure)", "Global variable" ) ", * There's an interesting question coming up, how does chrome know what the current local variables is when my code executes to line 20? * but also can give me categories, is not too wonderful???? But a closer look will give you an insight, and there must be a variable that holds the current variables, * otherwise, where does chrome go to read it? Right???????? *  Answer: * In fact, in each function there is a scope property, of course, this property is blocked by the engine, you can not see also touch, * it is stored in the current function of the local variables, if applied to the above demo, There is a scope in the global function, * Createcomparison has a scope, the anonymous compare has a scope, and the three scopes are still connected through the chain table, * Draw a diagram as follows: */

/** * As can be seen from the above diagram, in fact, the entire function has three scope, each scope is linked with the next pointer, thus forming a linked list, * When I execute the following code: * var result = Compare ({name: "D", age:20 }, {name: "C", age:27}); *  JS engine will get the current compare scope, through the scope property of the next pointer, you can distinguish which variables belong to which function, * so you see the chrome to variables categories. */

2. Deepen understanding

/** * 2, deepen understanding * In this example, I want to make an array of function () arrays, and finally can output their values (1,2,3,4,5...10), * But what about the results? Can see in the output is actually 10 a 10 ... That would violate my original intentions. * The biggest problem with this trap is that you think that I wrote return I in anonymous functions, and that it's an anonymous function, but it's a big mistake, because this I go to the ends of the earth is not an anonymous function, but belongs to its containing function person, * So the principle should be, like you see, when I execute arr[0] (), this time the anonymous function will go through scope to find I, but in the scope of the anonymous function * does not have I, so I found the person function through next, indeed found in the person I, But this time I was already 10, * and then ended the scope lookup output 10. * * solution is also very simple, give each anonymous function a copy is good, the specific principle I think you should be able to speculate with scope, right.        */var arr = new Array (), function person () {for (var i = 0; i <; i++) {//To remember, this property function declares that only immediate execution takes the scope property        var item = function () {return i;        };    Arr.push (item); }}person (); for (var i = 0; i < arr.length; i++) {Console.log (Arr[i] ());}        Change person () to the following, OK the function person () {for (var i = 0; i <; i++) {//To remember, this property function declares that only immediate execution takes the scope property            var item = function (num) {return function () {return num;        }} (i);    Arr.push (item); }}

 

--the effect after the change:

Note: This article originates from http://www.cnblogs.com/huangxincheng/p/4189843.html

Closures in JavaScript

Related Article

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.