Javascript scopes and closures

Source: Internet
Author: User

The nesting of scopes will form a scope chain, and the nesting of functions will form a closure. Closure and scope chain are an important feature that distinguishes JavaScript from other languages.

Scope
JavaScript has two scopes: function scope and global scope.

The variables declared in a function and the parameters of the function have the same scope, that is, the function scope. An example of a simple function scope:

Copy codeThe Code is as follows:
Function foo (){
Var bar = 1;
{
Var bar = 2;
}
Return bar; // 2
}

Unlike other languages with block scopes such as C, 2 is always returned here.

Global SCOPE. For the browser, it can be understood as the window object (Node. js is global ):
Copy codeThe Code is as follows:
Var bar = 1;
Function foo (){}
Alert (window. bar); // 1
Alert (window. foo); // "function foo (){}"

Both the variable bar and function foo belong to the global scope and are an attribute of window.

Scope chain
When accessing a variable in JavaScript, the scope will be traversed step by step from the local variables and parameters until the global scope.

Copy codeThe Code is as follows:
Var scope = 0, zero = "global-scope ";
(Function (){
Var scope = 1, one = "scope-1 ";
(Function (){
Var scope = 2, two = "scope-2 ";
(Function (){
Var scope = 3, three = "scope-3 ";
// Scope-3 scope-2 scope-1 global-scope
Console. log ([three, two, one, zero]. join (""));
Console. log (scope); // 3
})();
Console. log (typeof three); // undefined
Console. log (scope); // 2
})();
Console. log (typeof two); // undefined
Console. log (scope); // 1
})();
Console. log (typeof one); // undefined
Console. log (scope); // 0

In the function at the innermost layer, each variable can be traversed and output step by step. In the second-to-last function, the three variable cannot be retrieved through traversal, so undefined is output.

For example, if you want to pay for something, you will first touch your wallet. If you don't have it, you can ask your dad for it, if your dad does not, he will try again ,.... When your dad has no money to buy things, he will not come to you.

Closure
Define another function in a function, called function nesting. Function nesting forms a closure.

Closure and scope chain complement each other. Function nesting also forms a closure when multiple scopes of the chain relationship are generated.
Copy codeThe Code is as follows:
Function bind (func, target ){
Return function (){
Func. apply (target, arguments );
};
}

So how to understand the closure?

External functions cannot access embedded Functions
External functions cannot access the parameters and variables of embedded functions.
Embedded functions can access parameters and variables of external functions.
To put it another way: Nested functions include external function scopes.
Let's take a look at the previous example of the scope chain. This time we can understand from the perspective of closures:

Copy codeThe Code is as follows:
Var scope = 0, zero = "global-scope ";
(Function (){
Var scope = 1, one = "scope-1 ";
(Function (){
Var scope = 2, two = "scope-2 ";
(Function (){
Var scope = 3, three = "scope-3 ";
// Scope-3 scope-2 scope-1 global-scope
Console. log ([three, two, one, zero]. join (""));
Console. log (scope); // 3
})();
Console. log (typeof three); // undefined
Console. log (scope); // 2
})();
Console. log (typeof two); // undefined
Console. log (scope); // 1
})();
Console. log (typeof one); // undefined
Console. log (scope); // 0

The function at the innermost layer can access all its internal and external variables. The second-to-last function cannot access the variable at the innermost layer. At the same time, the value assignment of scope = 3 in the innermost layer does not affect the variable with the same name.

To understand the closure from another angle:

Each time an external function is called, an embedded function is created once.
When it is created, the scope of the external function (including any local variables, parameters, and other context) will become part of the internal state of each embedded function object, even after the external function is executed and exited
See the following example:

Copy codeThe Code is as follows:
Var I, list = [];
For (I = 0; I <2; I + = 1 ){
List. push (function (){
Console. log (I );
});
}
List. forEach (function (func ){
Func ();
});

We will get two "2" instead of the expected "1" and "2 ", this is because the variable I accessed by the two functions in the list is the same variable with the scope at the previous layer.

We changed the code to use the closure to solve this problem:

Copy codeThe Code is as follows:
Var I, list = [];
For (I = 0; I <2; I + = 1 ){
List. push (function (j ){
Return function (){
Console. log (j );
};
}) (I ));
}
List. forEach (function (func ){
Func ();
});

The outer "immediate execution function" receives a parameter variable I, which exists in the form of parameter j. It points to the same reference as the name j in the returned inner function. After the outer function is executed and exited, the parameter j (whose value is the current value of I at this time) becomes a part of the State of its inner function and is saved.

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.