JavaScript closures I don't know, you know, anyway, I understand. _javascript skills

Source: Internet
Author: User
Tags closure keep alive
Increasingly feel that there is no teaching and educating atmosphere, in order to understand the closure of JS, I resorted to my English four level of sucking the strength to Google to search for the closure of the package explanation, when I saw the StackOverflow on this one, my brain appeared in a sentence: it is the goods did not run!

See you in the next translation.

Peter Mortensen asked:

As old Albert says, "If you can't explain it to a six-year-old, you don't know it." "Well, I tried to be a 27-year-old friend is a JS closure (JavaScript closure) but completely failed."

How would you explain it to a six-year-old with a curiosity?

Note: I've seen the example given on StackOverflow, but it's no use at all.

Ali's Answer:

When a function is nested in a function, the internal function can access the variables in the external function.
Copy Code code as follows:

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

No matter how many times it is executed, alert 16 is available because bar can access the parameter X of foo and also access variable tmp of foo.

But this is not a closure. When you return an internal function, it is a closure. Internal function Close-over variables of external function until the internal function ends.
Copy Code code as follows:

function foo (x) {
var tmp = 3;
return function (y) {
Alert (x + y + (++tmp));
}
}
var bar = foo (2); Bar is now a closed pack
Bar (10);

The script above will eventually alert 16, because although bar is not directly within the scope of Foo, bar can 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.

(Given the six-year-old limit: We can actually create more than one closure method, such as return their arrays, or set them to global variables.) They all point to the same x and the same TMP, rather than having a copy of each. )

Note: Now to the whole seven-year-old content.

The above x is a literal (value pass), like other characters in JS, when Foo is called, the value of argument x is copied, and the copy is taken as the parameter X of foo.

So the problem is, JS processing object is used to pass the reference, then you call Foo when passing a Object,foo function return closure will also refer to the original object!
Copy Code code 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 closed package that references age.
Bar (10);

Not surprisingly, every time we run bar, X.MEMB will add 1. Note, however, that X points to the same object variable--age each time, and after running two bar (10), the AGE.MEMB becomes 2.

This is related to the memory leak of the HTML object, er, but it seems to be beyond the scope of the answer.

Johnmerlino said to Ali:

Here is an example of a closure that does not use the return keyword:
Copy Code code as follows:

function Closureexample (obj, text, timedelay) {
settimeout (function () {
document.getElementById (objid). InnerHTML = text;
}, Timedelay);
}
Closureexample (' mydiv ', ' Closure is created ', 500);

Late at night 1:37 John Pick replied:

The function in JS can access them:

1. Parameter

2. Local variables or functions

3. External variables (environment variables?), including

3.1 Global variables, including DOM

3.2 A variable or function of an external function.

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 (keep alive) these variables. In examples of internal functions and external functions, external functions can create local variables and eventually exit, but if any one or more internal functions do not exit after it exits, the intrinsic function maintains the local data of the external function.

A typical example is the use of global variables.

Mykhal this answer:

Wikipedia's definition of closures is this:

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

Technically, in JS, each function is a closure because it always accesses the data defined outside it.

Since scope-defining Construction in Javascript are a function, not a code blocks like in many other languages, what we Usua Lly mean by closure in Javascript are a fuction working with nonlocal variables defined in already executed surrounding Ction.

Closures are often used to create functions that contain hidden data (but not always).
Copy Code code as follows:

var db = (function () {
Creates a hidden object, this object holds some data
The object cannot be accessed from the outside
var data = {};
Create a function that provides some way 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 intrinsic function, which is a closed package
})();
db (' x '); Back to undefined
db (' x ', 1); Set data[' x ' to 1
db (' x '); Return 1
We can't access data, the object itself.
But we can set its members

See so many foreign Daniel's solution, do not know you know or do not understand, anyway, I understand.
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.