Javascript design pattern (2) Closure

Source: Internet
Author: User

Body

The concept of closure:

A closure is an expression (usually a function) that has many variables and is bound to these variables. Therefore, these variables are part of the expression.

The most common Closure


Copy codeThe Code is as follows:
Function (){
Var I = 0;
Return function (){
Alert (I ++ );
}
}
Var B = ();
For (var I = 0; I <3; I ++ ){
B ();
}


Before interpreting the code above, we should first accept the creation and execution process of a function.

Step 1: Define the function, set the environment, and create a scope chain. Now a is a global variable, only window

Step 2: execute a, first create the scope (. scope = a), then create the activity object (callObject), and put callObject to the top of the scope chain of a, so a's scope chain contains two objects (a and window)

Step 3: add an arguments attribute to the activity object and save the parameter value when a is called.

Step 4: Assign the parameters and internal variables to activity object.

JavascriptGC principle: if an object is no longer referenced, it will be recycled by GC. If two objects reference each other without interference, the two objects will also be recycled.

Summary:

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

2. (var B = a () when executing a, create scope a. scope = a and create a callObject object to add the scope of.

3. The arguments attribute is added to object a, and the I and return functions are assigned to the activity object.

4. When executing a, B points to the ruturn function value of a, and the local variable I in a referenced in B does not meet the GC collection standard, activity object a is not recycled. Therefore, B accesses I for the first time and can only access

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.