Javascript design Pattern (ii) closure _javascript tips

Source: Internet
Author: User
Body

The concept of closures:

A closure is an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.

The most common closures


Copy Code code as follows:

function A () {
var i=0;
return function () {
alert (i++);
}
}
var b=a ();
for (Var i=0;i<3;i++) {
b ();
}


Before interpreting the above code, accept the creation and execution of a function

The first step: Define the function, set the environment, create the scope chain (scope chain) Now A is a global variable, then a scope chain only window

Step two: Execute a, first create the scope (a.scope=a), then create the active object (CallObject), and place the CallObject at the top of the scope chain of a, so a scope chain contains two objects (A and window)

Step three: Add a arguments property to the active object and save the parameter value when you call a

Step Fourth: Assign the parameters and internal variables to the active object a

JAVASCRIPTGC principle: If an object is no longer referenced, the object is reclaimed by GC. If two objects are not interfering with each other, the two objects will also be reclaimed.

Summarize:

1. When first defining a, the scope chain of A is created (scope chain)

2, (var b=a ()) When executing a, create the scope a.scope=a and create the scope of CallObject object add a

3. The Arguments property is added to object A and the I and return functions are assigned to the active object

4, when a B is executed, it points to the Ruturn function value of a, and the local variable I in a, which is referenced in B, does not conform to the GC's recycling criteria, and the activity object A is not reclaimed, so B access I is the first object to access, and only in B.

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.