JavaScript closure model

Source: Internet
Author: User

JavaScript Closure Model

-----[Original Translation]2016-09-01 09:32:22

"One" closure is not mysterious

The purpose of this article is to use JavaScript code to illustrate closures in order to make it easy for ordinary developers to understand closures and not for expert or functional programming developers.

Once you have grasped the core idea of closure, it is no longer difficult to understand, however, just looking at a few theoretical documents or a theory-centric document will only make you the opposite.

This article is intended for developers who have some programming experience in mainstream programming languages and can read the following JavaScript functions:

1 function SayHello (name) {2     var text = ' Hello ' + name; 3     var function () {console.log (text);} 4     say (); 5 }
View Code

"II" Closure case

Two sentences summed up:

    • A closure is a function that supports the first-class function (first-class functions), a variable that can be referenced in its scope classes (the variable is declared first), assigned to another variable, passed as a parameter to other functions, or returned as the result of a function. Or--
    • A closure is a stack frame that is allocated when the function starts executing, and is not freed when the function returns (similar to ' stack frame ' being allocated on the heap instead of being allocated on the stack!). )。

The following code returns a reference to another function.

1 functionSayHello2 (name) {2     varText = ' Hello ' + name;//Local Variable3     varSay =function() {console.log (text);}4     returnsay;5 }6 varSay2 = SayHello2 (' Bob '));7Say2 ();//logs "Hello Bob"
View Code

Run Result: (--ps: Translator Add--)

Most developers are able to understand how a reference to a function in the code above is returned to a variable (say2). If you can't see it, then you need to learn the basics and not the closures. A C language developer will understand that a function returns a pointer to another function, and the variable say and say2 are pointers to two functions respectively.

In the C language, a pointer to a function is a key difference from a reference to a function in JavaScript. That is, in JavaScript, you can understand that a function reference variable is a pointer to a function and an implicit pointer to a closure.

There is a closure in the above code because the anonymous function functions () {console.log (text);} In other functions there are defined, and the instance is defined in the SayHeelo2 () function. In JavaScript, if you use the Function keyword in the other functions, you are creating a closure.

In C and other similar programming languages, when a function returns, all local variables are no longer available because the stack frame has been destroyed.

In JavaScript, if you declare another function in one function, the local variable can still be used after returning from the function you call. As shown above, because we are returning from SayHello2 () and then calling Say2 () Notice that the code we call has text in it, and this variable is SayHello2 () a local variable in the function.

Looking closely at the output of say2.tostring () , it is not difficult to see that this code refers to the text variable. The anonymous function can refer to textcontaining the value ' Hello Bob ' because the local variable of SayHello2 () is saved in the closure.

The mystery is that a function reference in JavaScript is also an implicit reference to a closure created in a function---like a delegate is a method pointer to an implicit reference that is added to an object.

More examples of the three

For some reason, when you look only at the relevant documents, it seems that closures are really difficult to understand, but when you combine some examples you can see exactly how they work (it may take us some time). It is advisable to study hard in practice until you understand how they work. If you use them without fully understanding how closures work, you probably have a lot of bad bugs.

Example 1:

This example demonstrates that local variables are not copied-they are saved in the reference. This is as if there is a function in memory to save a corresponding stack frame.

View Code

Example 1 running Result: (--ps: Translator added-)

Example 2:

Three global functions have a reference to the same closure, because they are all individually defined to invoke setupsomeglobals ().

Example 2 running Result: (--ps: Translator added-)



(translated from the StackOverflow community; original information: Morris Published: 2006-02-21)

Original link

JavaScript closure model

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.