JavaScript closures are hard to understand. Anyway, I understand _ javascript skills-js tutorial

Source: Internet
Author: User
Tags keep alive
If you cannot explain it clearly to a six-year-old, you do not understand it yourself. Well, I tried to tell a 27-Year-Old friend that the Javascript closure (JavaScriptclosure) has completely failed. I feel that there is no teaching and educating people in China. In order to understand the closure of JS, I tried to search google for the closure explanation. When I saw this answer on stackoverflow, I came up with a sentence: this product is not running!

I can't see the translation.

Peter Mortensen asked:

As Albert said, "If you cannot explain it clearly to a six-year-old, you don't understand it yourself ." Well, I tried to give a 27-Year-Old friend JavaScript closure a complete failure.

How do you explain it to a curious 6-year-old?

Note: I have read the example provided on StackOverflow, but it is useless.

Ali's answer:

When a function is nested in a function, the internal function can access the variables in the external function.

The Code is as follows:


Function foo (x ){
Var tmp = 3;
Function bar (y ){
Alert (x + y + (++ tmp ));
}
Bar (10 );
}
Foo (2)


Alert 16 will be executed no matter how many times, because bar can access the foo parameter x and the foo variable tmp.

However, this is not a closure. When you return an internal function, it is a closure. The internal function will close-over the variable of the external function until the internal function ends.

The Code is as follows:


Function foo (x ){
Var tmp = 3;
Return function (y ){
Alert (x + y + (++ tmp ));
}
}
Var bar = foo (2); // bar is now a closure
Bar (10 );


The above script will eventually use alert 16, because although bar is not directly in the internal scope of foo, bar can still access x and tmp.

However, because tmp still exists inside the bar closure, it will still add 1, and every time you call bar, it will add 1.

(Considering the limit of six years old: we can actually create more than one closure method, such as return their arrays, or set them as global variables. They all point to the same x and the same tmp, instead of having a copy .)

Note: Here is the content of the seven-year-old.

The above x is a nominal value (value transfer), which is the same as other nominal values in JS. When foo is called, the value of the real parameter x is copied, the copied copy is used as the foo parameter x.

Then the problem arises. When processing objects in JS, the reference is used for transmission. Therefore, when you call foo, an object is passed. The closure of the foo function return will also reference the original object!

The Code is as follows:


Function foo (x ){
Var tmp = 3;
Return function (y ){
Alert (x + y + tmp );
X. memb = x. memb? X. memb + 1: 1;
Alert (x. memb );
}
}
Var age = new Number (2 );
Var bar = foo (age); // bar is now a closure that references age
Bar (10 );


Unexpectedly, Every time bar (10) is run, x. memb will automatically add 1. However, note that x points to the same object variable -- age every time. After bar (10) is run twice, age. memb will change to 2.

This is related to memory leakage of HTML objects. However, it seems to be out of the answer range.

JohnMerlino told Ali:

Here is an example of a closure without the return Keyword:

The Code is as follows:


Function closureExample (obj, text, timedelay ){
SetTimeout (function (){
Document. getElementById (objID). innerHTML = text;
}, Timedelay );
}
ClosureExample ('mydiv ', 'Closure is created', 500 );


John Pick replied at in the middle of the night:

Functions in JS can access them:

1. Parameters

2. Local variables or functions

3. external variables (Environment Variables ?), Including

3.1 global variables, including DOM

3.2 External function variables or functions.

If a function accesses its external variables, it is a closure.

Note that external functions are not required. By accessing external variables, a closure can maintain these variables (keep alive. In the example of internal and external functions, external functions can create local variables and exit. However, if any one or more internal functions do not exit after they exit, the internal function maintains the local data of the external function.

A typical example is the use of global variables.

Mykhal replied:

Wikipedia defines closures as follows:

In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.

Technically, in JS, every function is a closure, because it can always access data defined externally.

Since scope-defining construction in Javascript is a function, not a code block like in your other ages, what we usually mean by closure in Javascript is a fuction working with nonlocal variables defined in already executed surrounding function.

Closures are often used to create functions that contain hidden data (but not always like this ).

The Code is as follows:


Var db = (function (){
// Create a hidden object that holds some data
// The object cannot be accessed from outside
Var data = {};
// Create a function that provides methods to access data
Return function (key, val ){
If (val = undefined) {return data [key]} // get
Else {return data [key] = val} // set
}
// We can call this anonymous method
// Returns this internal function, which is a closure.
})();
Db ('x'); // return undefined
Db ('x', 1); // set data ['X'] to 1
Db ('x'); // returns 1
// We cannot access the data object itself.
// But we can set its members.


After reading the answers from so many foreign experts, I don't know whether you understand it or not. I understand it anyway.

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.