JavaScript Closures--implementation

Source: Internet
Author: User

The official explanation for closures is that an expression (usually a function) with many variables and an environment that binds them is also part of the expression.

The popular point is:

    1. From a theoretical point of view: all functions. Because they are all created, the data in the upper context is saved. This is true even for simple global variables, because accessing a global variable in a function is equivalent to accessing a free variable, at which point the outermost scope is used.

    2. From a practical point of view: The following functions are considered closures:

      Even if the context in which it was created has been destroyed, it still exists (for example, an intrinsic function is returned from the parent function)
      A free variable is referenced in code (a free variable: A variable that is used in a function, but not a function parameter or a local variable of a function)
        function Testfreedom () {            var freedomvar = 1;            function inner (param) {                echo (pclosure1, param + freedomvar);//print results to Pclosure1            }          return inner;        }

For the inner function, Freedomvar belongs to the free variable.

One implementation
<p id= "Closure1" style= "color:red" ></p>
function echo (p, HTML) {            p.innerhtml + = html + ' <br/> ';        } function closure () {            var innervar = 0;            function inner () {                return ++innervar;            }            return inner;        }        var quote = closure ();        Echo (pclosure1, quote ()),//1        Echo (pclosure1, quote ());//2

First look at the results:

1, the result of the first quote function is 1, the second time is 2

2, inner nested inside the function closure, function closure return function inner

3, combined with the above closure practice angle characteristics, can be concluded that closure is a closed package

4. Function closure will not be recycled by GC after return, for the following reasons:

    1. Closure returns a reference to the function inner to quote

    2. The scope chain of the function inner contains a reference to the active object (activation_1) of the function closure, as shown in.

    3. Inner can access all the variables and functions defined in the closure

    4. function inner referenced by quote

    5. function inner and dependent function closure

Ii. General scope diagram

Three, the closure inside the approximate execution steps

1) Initializes the global object, the Window object, Variable object (a Mutable object in the global execution Environment) as the window object itself. Create a scope chain object, assuming Scope_1, which contains only the Window object

2) scanning JavaScript source code, from the results can be defined by the variable name, function object. Follow the scan sequence:

    1. The definition of the function closure is found, and the function object is created using this definition, and the scope chain to the creation process is scope_1. Adds the result to the window's property, with the name closure and the returned function object

    2. The variable quote is found, the quote property is added on the Window object, and the value is undefined

3) Execute function closure, get return value:

3.1 Create activation object, assumed to be activation_1; Create a new scope Chain, assuming that the first object in Scope_2,scope_2 is Activation_1 and the second object is a Window object

3.2 Processing the parameter list. Create a arguments object and set it, set arguments to Activation_1 's properties

3.3 Perform a process similar to step 2 for the closure function body:

    1. Find the variable Innervar, add the Innervar property on the Activation_1 object, and the value is undefined

    2. The definition of the function inner is found, the function object is created using this definition, and the scope Chain to the creation process is scope_2 (the scope Chain of the function closure). Adds the result to the Activation_1 property, with the name inner and the value returned as a function object. Inner's interior [[Scope]] is scope_2

3.4 Execute Innervar Assignment statement, assign value "0"

3.5 Execution Inner:

    1. Create a Activation object, assumed to be activation_2, and create a new scope Chain, assuming that the first object in Scope_3,scope_3 is Activation_2, followed by Activation_ 1. Window object (taken from fn2 [[Scope], i.e. scope_2)

    2. Processes the parameter list. Because inner does not have parameters, only properties that create arguments objects and set to Activation_2 are used

    3. Perform a process similar to step 2 for inner function body, no variable definition and function declaration found

    4. Executes the function body. For any one variable reference, search from Scope_3, in this example, Innervar will be found on activation_1

    5. Returns the return value of inner

3.6 Return Results

4) Printing Results

Demo Download:

http://download.csdn.net/download/loneleaf1/8019865

Resources:

http://www.nowamagic.net/librarys/veda/detail/1707 JavaScript Closures One: Introduction to Closures

http://www.nowamagic.net/librarys/veda/detail/1708 JavaScript Closures Second: implementation of closures

http://www.nowamagic.net/librarys/veda/detail/1709 JavaScript closure Its three: the use of closures

Http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html easy-to-understand JavaScript closure

http://page.renren.com/601017893/note/801095804 Javascript Closures

Http://kb.cnblogs.com/page/110782/Javascript closures--you know, I understand.

http://coolshell.cn/articles/6731.html Understanding JavaScript Closures

http://kb.cnblogs.com/page/105708/in-depth understanding of JavaScript closures (closure)

What is the difference between a http://www.zhihu.com/question/20032419 dynamic scope and a lexical domain?

HTTP://KANGAX.GITHUB.IO/COMPAT-TABLE/ES5/ECMASCRIPT5 Browser Compatibility table

http://www.nowamagic.net/librarys/veda/detail/1579 How we should understand how the JavaScript engine works

The practice of functional programming in Http://www.ibm.com/developerworks/cn/web/1006_qiujt_jsfunctional/JavaScript

Http://www.cnblogs.com/fool/archive/2010/10/19/1855266.html Understanding javascript_13_ Execution Model Detailed

Source: http://www.cnblogs.com/strick/p/3997898.html

JavaScript Closures--implementation

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.