JavaScript closures--you know, I understand, anyway. __java

Source: Internet
Author: User
Tags closure keep alive

"If you can't explain it to a six-year-old, you don't understand it at all," he said.
"Well, I tried to be a 27-year-old friend is a JS closure (JavaScript closure) but completely failed."

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 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 are you going to explain it to a six-year-old with a curious look?

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.

function foo (x) {
    var tmp = 3;
    function bar (y) {
        alert (x + y + (++tmp));
    }
    Bar (a);
}
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.

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 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 it will add 1 each time you call bar.

(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 in 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.

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
bar (10) that refers to age;

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:

function Closureexample (ObjID, text, timedelay) { 
    settimeout (function () { 
        document.getElementById (objid). InnerHTML = text; 
    }, Timedelay); 
 

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).

var db = (function () {
///Create a hidden object that holds some data//the
var data = {} that cannot access this object from the outside;
Create a function that provides a way to access data in the method return function
(key, Val) {
    if (val = = undefined) {return Data[key]}//get
  
   else {return Data[key] = val}//Set
    }
//We can call this anonymous method
//back to this internal function, which is a closure
}) ();

db (' x '); return undefined
db (' X ', 1);//Set data[' x ' to 1
db (' x ');//return 1
///We cannot access data this object itself
// But we can set its members to see so many foreign Daniel's answer, do not know you know or do not understand, anyway, I understand.
  
A summary of the closures is as follows:

(1) closure is a design principle, it through the analysis context, to simplify the user's invocation, so that users do not know the circumstances, to achieve his purpose;

(2) The online mainstream analysis of the closure of the article is actually and the closure principle of the reverse, If you need to know the closure of the details to use it, the closure is designed to fail,

(3) Learn as little as possible.

Original source: http://kb.cnblogs.com/page/110782/

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.