Javascript Closure (Closure)

Source: Internet
Author: User

Closure is a difficult and characteristic of Javascript language. Many advanced applications rely on closures for implementation.

The following are my study notes, which are useful for beginners of Javascript.

I. Scope of Variables

To understand closures, you must first understand the special variable scopes of Javascript.

Variables have two scopes: global variables and local variables.

The special feature of Javascript is that the function can directly read global variables.

Var n = 999;

Function f1 (){
Alert (n );
}

F1 (); // 999.

On the other hand, local variables in the function cannot be read outside the function.

Function f1 (){
Var n = 999;
}

Alert (n); // error

Note that you must use the var command when declaring variables in a function. If you don't need it, you actually declare a global variable!

Function f1 (){
N = 999;
}

F1 ();

Alert (n); // 999

2. How to read local variables from the outside?

For various reasons, we sometimes need to get local variables in the function. However, as we have already said, under normal circumstances, this cannot be done. It can only be implemented through a work und.

That is to define another function within the function.

Function f1 (){

Var n = 999;

Function f2 (){
Alert (n); // 999
}

}

In the code above, function f2 is included in function f1. All local variables in function f1 are visible to f2. But in turn, the local variables in f2 are invisible to f1. This is the unique "chain scope" structure (chain scope) of Javascript language. The sub-object will first look up the variables of all parent objects. Therefore, all variables of the parent object are visible to the child object, and vice versa.

Since f2 can read local variables in f1, As long as f2 is taken as the return value, we can't read its internal variables outside f1!

Function f1 (){

Var n = 999;

Function f2 (){
Alert (n );
}

Return f2;

}

Var result = f1 ();

Result (); // 999.

Iii. Concepts of closures

The f2 function in the previous code is the closure.

Closure definitions in various professional documents are very abstract and hard to understand. In my understanding, closures are functions that can read internal variables of other functions.

In Javascript, only the subfunctions in a function can read local variables. Therefore, you can simply understand the closure as a function defined in a function ".

Therefore, in essence, closure is a bridge connecting the internal and external functions of a function.

Iv. Use of closures

Closures can be used in many places. It has two major functions: one is to read the internal variables of the function mentioned above, and the other is to keep the values of these variables in the memory.

How can we understand this sentence? See the following code.

Function f1 (){

Var n = 999;

NAdd = function () {n + = 1}

Function f2 (){
Alert (n );
}

Return f2;

}

Var result = f1 ();

Result (); // 999.

NAdd ();

Result (); // 1000.

In this Code, the result is actually the f2 function of the closure. It runs twice in total. The first value is 999, and the second value is 1000. This proves that the local variable n in function f1 has been stored in the memory and is not automatically cleared after f1 is called.

Why? The reason is that f1 is the parent function of f2, and f2 is assigned a global variable, which causes f2 to always be in the memory, while f2 depends on f1, therefore, f1 is always in the memory and will not be recycled by the garbage collection mechanism after the call is completed.

Another noteworthy part of this code is "nAdd = function () {n + = 1}". The var keyword is not used before nAdd, therefore, nAdd is a global variable rather than a local variable. Secondly, the value of nAdd is an anonymous function, and this anonymous function itself is also a closure, so nAdd is equivalent to a setter, you can operate the local variables inside the function outside the function.

5. Notes on using closures

1) because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause the performance of the web page, memory leakage may occur in IE. The solution is to delete all unused local variables before exiting the function.

2) The closure changes the value of the internal variable of the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its Public Method, and use internal variables as its private value ), be sure not to change the value of the internal variable of the parent function.

Vi. Questions

If you can understand the running results of the following two sections of code, you should understand the operating mechanism of the closure.

Code snippet 1.

Var name = "The Window ";

Var object = {
Name: "My Object ",

GetNameFunc: function (){
Return function (){
Return this. name;
};

}

};

Alert (object. getNameFunc ()());


Code snippet 2.

Var name = "The Window ";

Var object = {
Name: "My Object ",

GetNameFunc: function (){
Var that = this;
Return function (){
Return that. name;
};

}

};

Alert (object. getNameFunc ()());

 

 

 

 

 

 

 

 

 

 

 

 


JavaScript scope chain

 


<Script type = "text/javascript">

Var I = "w I ";

/*
Lexical Scoping)
Functions in JavaScript run in their defined scopes, rather than in their executed scopes.

This scope is called [[scope].
[[Scope] of non-embedded functions are all host objects, and different hosts have different contents.
*/
Var a = function (){
Alert (I );
}

Var B = function (){
Var I = "B I ";
A ();
}

Var c = function (){
A ();
}

A ();
/*
When a function is running, a call Object is created first,
Add the form parameters, variables, and function declaration results of the function to the call Object as attributes;
Add the call Object to the beginning of the function's scope chain;
Then, add [[scope] of Function Definition to its scope chain;

Search for identifiers in the function body
First, find the first object in Scope Chain. If yes, return. Otherwise
Continue to search for the next object. If the next object exists, return. Otherwise (repeat this step)
Undefined is returned If no result is found.
*/


B ();
C ();

/*
The scope Chain mechanism in JavaScript enables closure implementation
*/
Var d = function (){
Var I = "d I ";
Var e = function (){
Alert (I );
}
Return e;
}

Var f = d ();
F ();
/*
F is a reference of function e.
Call Object: no parameters, variable declarations, and internal functions;
[[Scope] Part: e is defined in function d. You can access d, I, e, in [[scope] of function e, then d will have a [[scope], which can be accessed in the upstream mode to form a chain.
*/

</Script>

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.