Understand javascript_15_scope allocation and variable access rules, and then send a closure

Source: Internet
Author: User

Scope allocation and variable access rules
In ECMAScript, functions are also objects. Function objects are created based on the Function declaration during variable instantiation, or when a Function expression is calculated or a Function constructor is called. (For 'function object', see Understanding Javascript_08 _ function objects.) Each function object has an internal [scope] attribute, which is also composed of an object list (chain. The internal [scope] attribute references the scope chain for creating their execution environment. At the same time, the active objects in the current execution environment are added to the top of the Object List. When we access variables within a function, it is actually the process of searching for variables on the scope chain.

The theory is too strong (I am in summary !), Let's take a look at the Code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function outer (){
Var I = 10;
Function inner (){
Var j = 100;
Alert (j); // 100
Alert (I); // 10
Alert (adf );
}
Inner ();
}
Outer ();
</Script>

Clearly shows the memory allocation and scope allocation of the above Code:

The following is an explanation:
1. Load the code and create a global execution environment. In this case, the outer variable is added to the variable Object window, which points to the function object outer. In this case, only the window object is included in the scope chain.
2. Execute the code. When the program runs to outer (), it searches for the outer variable in the Global Object and calls it successfully.
3. create an outer execution environment. A new activity object is created. Add variable I, set the value to 10, add variable inner, and point to function object inner. and push the activity object into the scope chain. and direct the [[scope] attribute of the function object outer to the active object outer. At this time, the scope chain is the activity object of outer + window.
4. Run the code and assign a value to I. When the program runs into inner (), it searches for inner variables in [[scope] of the function object outer. It is successfully called after it is found.
5. create an inner execution environment, create an activity object, add the variable j, assign a value of 100, and push the activity object into the scope chain, and the [[scope] attribute of the function object inner points to the inner of the activity object. in this case, the scope chain is: inner's activity object + outer's activity object + global object.
6. the Execution Code is assigned a value for j. When I and j are accessed, the corresponding value is successfully found in the scope and output. When the access variable adf is not found in the scope, an access error occurs.

Note: Through the memory diagram, we will find that the scope chain and prototype chain are so similar. This explains a lot of questions !)

Closure Principle
After learning about the scope, it is very easy to solve the closure problem. What is a closure? A closure is an internal function that closes the variables in the scope of an external function.
Let's look at a typical closure application: generating increment values
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var increment = (function (){
Var id = 0;
Return function (){
Return ++ id;
}
})()
Alert (increment (); // 1
Alert (increment (); // 2
</Script>

The external anonymous function returns an embedded function that uses the local variable id of the external anonymous function. According to the principle, the local variables of the outer anonymous function are out of the scope when they are returned, so the increment () call cannot be used. This is the Closure, that is, the function call returns an embedded function, and the embedded function references the external function's local variables, parameters, and other resources that should be closed. What is this? Let's look for the answer:

According to the understanding of Scope Chain, the returned nested functions already hold the Scope Chain when constructing it. Although the returned outer results in these objects exceeding the Scope and lifetime range, however, JavaScript uses automatic garbage collection to release the object memory: regular checks are performed according to the rules, and objects are released without any reference. Therefore, the above Code can run correctly.

Refer:
Http://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.html
Http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html

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.