Deep understanding of JavaScript closure Concepts __java

Source: Internet
Author: User
Tags closure
Closures have always been a mysterious and profound feeling to programmers, including JavaScript programmers, and in fact, the concept of closures is not an incomprehensible knowledge in functional programming languages. If the basic concepts such as the scope, the function for the independent object understood better, the understanding closure concept and in the actual programming practice application is quite ripe for the feeling.

In the case of DOM, most programmers are already using closures rather than themselves, and in such cases, the problem of the JavaScript engine embedded in the browser may result in a memory leak, or the programmer's own debugging is often confused.

Describe the concept of closures in JavaScript with simple statements: Because in JavaScript, a function is an object, an object is a collection of attributes, and the value of a property can be an object, it is a matter of course to define a function within a function, if the function is declared inside a function func inner, It then invokes inner outside the function, which creates a closure.

Characteristics of closures
Let's take a look at an example where it's hard to find out why you don't know the features of javascript:
var outter = [];
function Clousetest () {
var array = ["One", "two", "three", "four"];
for (var i = 0; i < array.length;i++) {
var x = {};
x.no = i;
X.text = Array[i];
X.invoke = function () {
print (i);
}
Outter.push (x);
}
}

Call this function
Clousetest ();

Print (Outter[0].invoke ());
Print (Outter[1].invoke ());
Print (Outter[2].invoke ());
Print (Outter[3].invoke ());
What about the results of the operation. Many beginners may come up with the answer:
0
1
2
3

However, the results of running this program are:
4
4
4
4

In fact, in each iteration, such statements x.invoke = function () {print (i);} is not executed, just constructs a function body for "print (i);" Function object, that's all. And when i=4, the iteration stops, the external function returns, and when the Outter[0].invoke () is invoked, the value of I is still 4, so the invoke of each element in the Outter array returns the value of I: 4.

How to solve this problem. We can declare an anonymous function and execute it immediately:
var outter = [];

function ClouseTest2 () {
var array = ["One", "two", "three", "four"];
for (var i = 0; i < array.length;i++) {
var x = {};
x.no = i;
X.text = Array[i];
X.invoke = function (NO) {
return function () {
print (no);
}
} (i);
Outter.push (x);
}
}

ClouseTest2 ();

In this example, when we assign a value to X.invoke, we run a function that can return a function, and then execute it immediately, so that each iteration of the X.invoke is equivalent to executing such a statement:
x = = 0
X.invoke = function () {print (0);}
x = = 1
X.invoke = function () {print (1);}
x = = 2
X.invoke = function () {print (2);}
x = = 3
X.invoke = function () {print (3);}
So that we can get the correct result. Closures allow you to reference variables that exist in external functions. However, instead of using the variable when it was created, it uses the last value of the variable in the external function.

Use of closures
Now that the concept of closure is clear, let's look at the purpose of closures. In fact, we can do a lot of things by using closures. For example, simulate object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.

Anonymous self-execution function
The example in the previous section, in fact, a use of closures, according to the foregoing, all variables, if not with the VAR keyword, the default will be added to the properties of the global object, such a temporary variable to join the global object has many disadvantages, such as: Other functions may misuse these variables Causing the global object to be too large to affect the access speed (because the variables are taken from the prototype chain). In addition to using the var keyword for each variable, we often encounter situations where a function needs to be executed only once and its internal variables need not be maintained, such as the UI initialization, so we can use closures:
var Datamodel = {
Table: [],
Tree: {}
};

(function (DM) {
for (var i = 0; i < dm.table.rows; i++) {
var row = Dm.table.rows[i];
for (var j = 0; j < Row.cells; i++) {
Drawcell (i, j);
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.