Understand javascript_15_ scope assignment and variable access rules, and then send a closure "turn"

Source: Internet
Author: User

Before reading this blog post, please read "Understanding javascript_13_ Execution Model"

The issue of scope assignment is covered in ' execution model details ', and this post will detail the relationship between the function object, the scope chain, and the execution context.

Scope assignment and variable access rules

In ECMAScript, the function is also an object. A function object is created during the instantiation of a variable according to a function declaration, or when a function expression is evaluated or a constructor is called Function . (see "Understanding javascript_08_ Function Objects" for "function objects"). Each function object has an internal [[scope]] property, which is also made up of a list of objects (chains). This internal [scope] property refers to the scope chain of the execution environment in which they are created, while the active object of the current execution environment is added to the top of the list of objects. When we access variables inside a function, we are actually looking for variables on the scope chain.

The theory is too strong (summed up dead me!) Or let's take a look at some code:

12345678910111213 <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:

Here's an explanation:

1. Load the code to create the global execution environment, where the outer variable is added to the Variable Object (window), which points to the function object outer, when only the Window object is in the scope chain.

2. Executes the code, and when the program executes to outer (), it looks for the outer variable in the global object, which is successfully invoked.

3. Create an execution environment for outer, at which time a new active object is created, the variable i is added, the value is 10, the variable inner is added, and a pointer to the function object inner. And the active object is pressed into the scope chain. And the function object is outer [[scope]] The outer property points to the active object. This time the scope chain is Outer's active object +window.

4. Execute the code, assign the value to I successfully. When the program executes to inner (), it looks for the inner variable in the function object outer [[scope]]. Successfully called after it is found.

5. Create a inner execution environment, new Activity object, add variable j, assign a value of 100, and press the active object into the scope chain, and the function object inner the [[scope]] property to the active object inner. The scope chain is now: Inner active object + Outer the active object + global object.

6. The execution code is a J assignment, and when access to I, J succeeds in locating the corresponding value in the scope and outputting, and when accessing the variable ADF, there is no access error in the scope.

Note: Through the memory graph, we will find that the scope chain is so similar to the prototype chain. This shows a lot of problems ... (Benevolent See, explore the answers yourself!) )

Closure principle

After we understand the scope of the problem, the closure of the problem is very simple. What is a closure package? Closures are intrinsic functions that enclose variables in the scope of an external function.

Let's look at a typical closure application: Generate increment values

1234567891011 < script  type= "text/javascript"; var increment = (function () { &NBSP;&NBSP;&NBSP;&NBSP; var id = 0; &NBSP;&NBSP;&NBSP;&NBSP; return function () {           return ++id; &NBSP;&NBSP;&NBSP;&NBSP; } }) ()  alert ( Increment ());//1 alert (increment ());//2 </ script >

The outer anonymous function returns an inline function that uses the local variable ID of the outer anonymous function. The local variable of the enclosing anonymous function is out of scope when it is returned, so the increment () call cannot be used. This is the closure closure, that is, the function call returns an inline function, while the inline function references the external function's local variables, parameters, and so on that should be closed (close) resources. What's the matter? Let's look for answers:

Based on the understanding of scope Chain, it can be explained that the returned inline function already holds the scope Chain when it was constructed, although outer returns cause these objects to be out of scope, lifetime scope, but JavaScript uses automatic garbage collection to release object memory: Periodic checks are followed by rules, and objects are freed without any references. So the above code will work correctly.

Reference:

123 <ahref="http://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.htmlhttp://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html">http://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.htmlhttp://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html</a>

Understand javascript_15_ scope assignment and variable access rules, and then send a closure "turn"

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.