Javascript closures _ basic knowledge

Source: Internet
Author: User
This article mainly introduces the detailed description of the closure of Javascript. if you need it, you can refer to the Preface: It is also an introductory article. Javascript has several very important language features: Object, prototype inheritance, and closure. Closure is a new language feature for programmers who use traditional static language C/C ++. This article will start with an example to introduce the language features of Javascript closures, and combine with a little ECMAScript language specification to enable readers to better understand closures.

Note: This article is an introductory article. The example materials are organized on the internet. if you are a master, you are welcome to provide technical suggestions and comments for this article. This article discusses Javascript and does not want to compare the language. if you are not comfortable with Javascript, Please bypass it yourself.

What is a closure?
What is a closure? The Closure is Closure, which is a new feature not available in static languages. However, closures are not complicated to be incomprehensible. In short, closures are:

Closure is the set of local variables of the function, but these local variables will continue to exist after the function returns.
The closure is the "stack" of the function that is not released after the function is returned. we can also understand that these function stacks are not allocated on the stack but on the stack.
When another function is defined in a function, a closure is generated.
The second definition above is the first supplementary description. the closure of the first definition is the 'local variable 'set of the function. This local variable can be accessed after the function returns. (This is not an official definition, but it should help you better understand the closure)

As a local variable, it can be accessed by the code in the function. this is no different from the static language. The difference between closure is that local variable can still be accessed by code outside the function after the function execution is complete. This means that the function must return a "reference" pointing to the closure, or assign this "reference" to an external variable to ensure that the partial variables in the closure are accessed by external code. Of course, the entity that contains this reference should be an object, because in Javascript, all objects except the basic types are left. Unfortunately, ECMAScript does not provide related members and methods to access the partial variation in the closure. However, in ECMAScript, the internal function defined in the function object is a local variable that can directly access external functions. through this mechanism, we can access the closure in the following way.

The code is as follows:


Function greeting (name ){
Var text = 'hello' + name; // local variable
// Each call generates a closure and returns an internal function object to the caller.
Return function () {alert (text );}
}
Var sayHello = greeting ("Closure ");
SayHello () // access the local variable text through the closure

The execution 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 is executed.

Well, this is the effect of closures in the legend. closures have multiple application scenarios and patterns in Javascript, such as Singleton and Power Constructor.

ECMAScript closure model
How does ECMAScript implement closures? If you want to know more about it, you can obtain the ECMAScript specification for research. here I will also give a simple explanation, the content also comes from the network.

When a function of ECMAscript script is run, each function Association has an Execution Context, which contains three parts.

The LexicalEnvironment)
The VariableEnvironment)
This binding
The third point of this binding is irrelevant to the closure, which is not discussed in this article. The variable identifier used to parse the function execution process in the grammar environment. We can think of a grammar environment as an object. this object contains two important components: environment Recode and external reference ). The environment record contains the local variables and parameter variables declared inside the function. the external reference points to the context execution scenario of the external function object. In a global context scenario, the reference value is NULL. Such a data structure forms a one-way linked list. each reference points to an outer context scenario.

For example, the closure model in the above example should be like this. the sayHello function is at the bottom layer, the greeting function is at the upper layer, and the global scenario is at the outermost layer. For example, when sayHello is called, sayHello finds The text value of The local variable in The context scenario. Therefore, The "Hello Closure" variable environment (The VariableEnvironment) is displayed in The dialog box on The screen) similar to the syntax environment, see the ECMAScript standard document for specific differences.

Example column of closure
I have a general understanding of what Javascript closures are and how closures are implemented in Javascript. The following examples help you better understand Closures. There are five examples in the following: JavaScript Closures For Dummies (image ). Example 1: local variables in the closure are referenced rather than copied.

The code is as follows:


Function say667 (){
// Local variable that ends up within closure
Var num = 666;
Var sayAlert = function () {alert (num );}
Num ++;
Return sayAlert;
}

Var sayAlert = say667 ();
SayAlert ()

Therefore, the execution result should display 667 instead of 666.

Example 2: multiple functions are bound to the same closure because they are defined in the same function.

The code is as follows:


Function setupSomeGlobals (){
// Local variable that ends up within closure
Var num = 666;
// Store some references to functions as global variables
Required tnumber = function () {alert (num );}
GIncreaseNumber = function () {num ++ ;}
GSetNumber = function (x) {num = x ;}
}
SetupSomeGlobals (); // assign values to three global variables
Required tnumber (); // 666
GIncreaseNumber ();
Required tnumber (); // 667
GSetNumber (12 );//
Required tnumber (); // 12

Example 3: When a function is assigned in a loop, these functions are bound to the same closure.

The code is as follows:


Function buildList (list ){
Var result = [];
For (var I = 0; I <list. length; I ++ ){
Var item = 'ITEM' + list [I];
Result. push (function () {alert (item + ''+ list [I])});
}
Return result;
}
Function testList (){
Var fnlist = buildList ([1, 2, 3]);
// Using j only to help prevent confusion-cocould use I
For (var j = 0; j <fnlist. length; j ++ ){
Fnlist [j] ();
}
}

The execution result of testList is three times that the item3 undefined window pops up, because the three functions are bound to the same closure and the item value is the final calculation result, but when I jumps out of the loop, the I value is 4, so the result of list [4] is undefined.

Example 4: all local variables of an external function are in the closure, even if the variable is declared after the definition of an internal function.

The code is as follows:


Function sayAlice (){
Var sayAlert = function () {alert (alice );}
// Local variable that ends up within closure
Var alice = 'Hello Alice ';
Return sayAlert;
}
Var helloAlice = sayAlice ();
HelloAlice ();

The execution result is displayed in the "Hello Alice" window. Even if the local variable is declared after the sayAlert function, the local variable can still be accessed.

Example 5: create a new closure for each function call

The code is as follows:


Function newClosure (someNum, someRef ){
// Local variables that end up within closure
Var num = someNum;
Var anArray = [1, 2, 3];
Var ref = 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 [3,990,] ref: 'somevar closure2'

Closure Application
Singleton:

The code is as follows:


Var singleton = function (){
Var privateVariable;
Function privateFunction (x ){
... PrivateVariable...
}

Return {
FirstMethod: function (a, B ){
... PrivateVariable...
},
SecondMethod: function (c ){
... PrivateFunction ()...
}
};
}();

This single piece is implemented through the closure. The closure is used to encapsulate private members and methods. The anonymous Main function returns an object. The object contains two methods: Method 1 can be a private variable, and method 2 can be used to access internal private functions. Note that '()' is at the end of the anonymous main function. without this '()', a single piece cannot be generated. Because the anonymous function can only return unique objects and cannot be called elsewhere. This is the method of using closures to generate a single piece.

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.