Home >Web Front-end >JS Tutorial >Javascript Design Pattern (2) Closure_javascript skills

Javascript Design Pattern (2) Closure_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:26:12926browse

Text

The concept of closure:

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

The most common closures


Copy code The code is as follows:

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


Before explaining the above code, first accept a The creation and execution process of the function

The first step: define the function, set the environment, and create the scope chain. Now a is a global variable, then the scope chain of a only has window

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

Step 3: Add an arguments attribute on the active object to save the parameter value when calling a

Step 4: Assign formal parameters and internal variables Go to active object a

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

Summary:

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

2. (var b=a()) executes a When creating the scope a.scope=a, create a callObject object and add it to the scope of a

3. Add the arguments attribute to the a object, and assign the i and return functions to the active object

4. When a is executed, b points to the ruturn function value of a, and b refers to the local variable i in a. Therefore, it does not meet the GC recycling standards. The active object a is not recycled, so b accesses i. is the object accessed for the first time and can only be accessed in b
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn