Understanding the closure of JavaScript

Source: Internet
Author: User

Preface: It is also an introductory article. There are several very important language features in JavaScript-objects, prototype inheritance, closures. Closures are a new language feature for programmers who use the traditional static language, C + +. This article will introduce the language features of JavaScript closures with examples, and combine a bit of ECMAScript language specification to enable readers to understand closures more deeply.

Note: This article is an introductory article, examples of material in the network , if you are a master, welcome to the article to provide technical advice and advice. This article discusses JavaScript and does not want to be a language contrast, and if you are naturally uncomfortable with JavaScript, make your own detour.

What is a closure package

What is a closure? Closures are closure, which is a new feature that static languages do not have. But closures are not complex and incomprehensible things, in short, closures are:

    • A closure is a set of local variables for a function, except that these local variables will continue to exist after the function returns.
    • Closures are just the "stacks" of functions that are not released after the function is returned, and we can also understand that these function stacks are not allocated on the stack but are allocated on the heap
    • A closure is generated when another function is defined within a function

The second definition above is the first additional explanation, extracting the first defined principal predicate--the closure is the ' local variable ' collection of the function . Just this local variable can be accessed after the function is returned. (This is not an official definition, but this definition should be better for you to understand closures)

The

As a local variable can be accessed by the code within the function, which is no different from the static language. The difference between closures is that local variables can still be accessed by code outside the function at the end of the function execution. This means that the function must return a reference to the closure, or assign the reference to an external variable to ensure that the local variables in the closure are accessed by external code. Of course, the entity that contains this reference should be an object, because in JavaScript the remainder of the basic type is the object. Unfortunately, ECMAScript does not provide the relevant members and methods to access the local variables in the closure. However, in ECMAScript, the intrinsic function (inner) defined in the function object is a local variable that can directly access the external function, and through this mechanism, we can complete the access to the closure in the following way.

1234567 function   Greeting ( Name) {      var   text =  ' Hello '

The result of the above code is: Hello Closure, because the SayHello () function can still access the local variable text defined within it after the greeting function has finished executing.

Well, this is the legend of the closure effect, closures in JavaScript has a variety of application scenarios and patterns, such as Singleton,power constructor and other JavaScript patterns are inseparable from the use of closures.

ECMAScript closure Model

How does the ECMAScript implement closures? Want to learn more about the pro can get ECMAScript specifications for research, I also only do a simple explanation, the content is from the network.

When the ECMAScript script function runs, each function association has an execution context scenario (execution context) that contains three parts in the execution context scenario

    • Grammar environment (the lexicalenvironment)
    • Variable environment (the variableenvironment)
    • This binding

Where the 3rd this binding is not related to closures, it is not discussed in this article. The variable identifier used in the grammar environment for parsing function execution. We can think of the grammatical environment as an object that contains two important components, an environment record (enviroment Recode), and an external reference (pointer). The environment record contains local variables and parameter variables that contain the internal declaration of the function, and the external reference points to the context execution scenario of the external function object. This reference value is NULL in a global context scenario. Such a data structure constitutes a one-way list, each of which points to the outer context of the scenario.

For example, the closure model of our example above should be this way, the SayHello function is at the bottom, the upper layer is the function greeting, the outermost is the global scene. For example: So when SayHello is called, SayHello will find the value of the local variable text in context, so the "Hello Closure" variable environment (the Variableenvironment) is displayed in the dialog box on the screen. Similar to the role of the grammar environment, please refer to the ECMAScript specification document for specific differences.

the sample of a closed packet

I have a rough idea of what JavaScript closures are, and how closures are implemented in JavaScript. Below we have some examples to help you understand the closure, a total of 5 samples, examples from the JavaScript Closures for Dummies (mirror). Example 1: A local variable in a closure is a reference, not a copy

12345678910 functionsay667() {    // Local variable that ends up within closure    var num = 666;    var sayAlert = function() { alert(num); }    num++;    return sayAlert;} var  sayAlert = say667();sayAlert()

So the execution result should pop up 667 instead of 666.

Example 2: Multiple functions bind the same closure because they are defined within the same function.

1234567891011121314 functionsetupSomeGlobals() {    // Local variable that ends up within closure    varnum = 666;    // Store some references to functions as global variables    gAlertNumber = function() { alert(num); }    gIncreaseNumber = function() { num++; }    gSetNumber = function(x) { num = x; }}setupSomeGlobals(); // 为三个全局变量赋值gAlertNumber(); //666gIncreaseNumber();gAlertNumber(); // 667gSetNumber(12);//gAlertNumber();//12

Example 3: When assigning functions in a loop, these functions will bind the same closures

12345678910111213141516 functionbuildList(list) {    varresult = [];    for(vari = 0; i < list.length; i++) {        varitem = ‘item‘+ list[i];        result.push( function() {alert(item + ‘ ‘+ list[i])} );    }    returnresult;}functiontestList() {    varfnlist = buildList([1,2,3]);    // using j only to help prevent confusion - could use i    for(varj = 0; j < fnlist.length; j++) {        fnlist[j]();    }}

The result of the testlist is to eject the item3 undefined window three times, because these three functions bind the same closure, and the value of item is the result of the last calculation, but when I jumps out of the loop I value is 4, so the result of list[4] is undefined.

Example 4: External function All local variables are inside the closure, even if the variable is declared after the intrinsic function definition.

12345678 functionsayAlice() {    var sayAlert = function() { alert(alice); }    // Local variable that ends up within closure    var alice = ‘Hello Alice‘;    return sayAlert;}var  helloAlice=sayAlice();helloAlice();

The result of the execution is a window that pops up "Hello Alice". Even if a local variable is declared after the function Sayalert, the local variable can still be accessed.

Example 5: Create a new closure each time the function is called

123456789101112131415161718 functionnewClosure(someNum, someRef) {    // Local variables that end up within closure    varnum = someNum;    varanArray = [1,2,3];    varref = someRef;    return function(x) {        num += x;        anArray.push(num);        alert(‘num: ‘+ num +        ‘\nanArray ‘+ anArray.toString() +        ‘\nref.someVar ‘+ ref.someVar);    }}closure1=newClosure(40,{someVar:‘closure 1‘});closure2=newClosure(1000,{someVar:‘closure 2‘});closure1(5); // num:45 anArray[1,2,3,45] ref:‘someVar closure1‘closure2(-10);// num:990 anArray[1,2,3,990] ref:‘someVar closure2‘
Application of Closures

Singleton single piece:

123456789101112131415 var singleton = function () {    var privateVariable;    function privateFunction(x) {        ...privateVariable...    }    return {        firstMethod: function (a, b) {            ...privateVariable...        },        secondMethod: function (c) {            ...privateFunction()...        }    };}();

This single piece is implemented by a closure package. The encapsulation of private members and methods is accomplished through closures. The anonymous main function returns an object. The object contains two methods, Method 1 can method private variables, and Method 2 accesses internal private functions. Note that the place where the anonymous main function ends is ' () ' and cannot produce a single piece without this ' () '. Because an anonymous function can only return a unique object, it cannot be called elsewhere. This is the use of closures to produce a single piece of the method.

Understanding the closure of JavaScript

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.