On JavaScript scope chain, execution context and closure _javascript skills

Source: Internet
Author: User
Tags closure function definition variable scope

Closures and scope chain is a more important concept in JavaScript, these two days to read some information, the relevant knowledge points to the following summary.

JavaScript takes the lexical scope (lexical scoping), where the function execution depends on the variable scoped by the function definition, not when the function is executed. As an example of the following code fragment, generally (based on the implementation of the stack, such as C language) Foo is called, the local variable scope within the function is released, but the lexical view of the embedded anonymous function in Foo should refer to the local variable scope of Foo, and the actual code run The result is consistent with the lexical expression, and the F is invoked to return the local scope. The function object F, after the end of its principal function Foo call, still holds the reference to the scope variable of the Foo function body, which is called the closure.

var scope = ' global scope ';
function foo () {
var scope = ' local scope ';
return function () {return
scope;
}
}
var f = foo ();
f (); Return to "local scope"

So how does closure work in the end? Understanding closures requires first understanding of variable scope and scope chain, and another important concept is the execution of context environments.

Variable scope

Global variables in JavaScript have global scope, the scope of variables declared in the function body is the entire function body, is local, and certainly includes nested functions defined in the function body. Local variables in the function body have precedence over global variables, and global variables are masked by local variables if the local variable has the same name as the global variable; The local variable defined within the nested function has precedence over the local variable of the function that contains the nested function. This is simply obvious and almost everyone knows it.
Next talk may be unfamiliar to everyone.

function declaration elevation

Using a sentence to illustrate the function of the declaration of Ascension, refers to the function of the internal declaration of variables and the entire function within the validity. In other words, the variable that is declared at the bottom of the function body is also elevated to the top. As an example:

var scope = ' global scope ';
function foo () {
console.log (scope);//This does not print "global scope", but "undefined"
var scope = ' local scope '; 
Console.log (scope); Obviously, print out "local scope"
}
foo ();

The first Console.log (scope) prints out the undefined instead of global scope because the declaration of the local variable is promoted, but not yet assigned.

As a variable of a property

In JavaScript, there are three ways to define global variables, such as GlobalVal1, GlobalVal2, and globalValue3 in the example code below. An interesting phenomenon is that the global variable is simply a property of the global object Window/global (the window in the browser, the global in Node.js). In order to be more consistent with the usual meaning of variable definitions, JAVASCRIPT uses the global variables defined by VAR to design a global object property that cannot be deleted. The Object.getownpropertydescriptor (this, ' globalVal1 ') can be obtained and its configurable property is false.

var globalVal1 = 1; Non-deleted global variable
globalVal2 = 2;//removable global variable
this.globalvalue3 = 3;//globalValue2 delete
globalVal1;//=> False variable not deleted delete
GlobalVal2//=> true variable deleted delete
this.globalvalue3;//=> true variable deleted

So the question is, does the local variable defined in the function Body also act as a property of an object? The answer is yes. This object is associated with a function call, which is referred to in ECMAScript 3 as "Call Object", ECMAScript 5, which is called "Declaravite environment Record". This particular object is an invisible internal realization for us.

Scope chain

As we know from the previous section, a function local variable can be a property of an object that is not visible. Then the implementation of the JavaScript lexical scope can be described as follows: Each section of JavaScript code (global or function) has a chain of scopes associated with it, which can be an array or a linked list structure; Each element in the scope chain defines a set of variables within a scope; When we want to find the variable x Value, find the variable from the first element in the scope chain, if no one finds the next element in the list until it finds or reaches the end of the chain. Understanding the concept of scope chains is critical to understanding closures.

Execution context

The execution of each piece of JavaScript code is bound to the execution context, and the running code receives the variables, functions, data, and so on that are available through the execution context. The global execution context is unique, bound to global code, and each execution of a function creates an execution context and its binding. JavaScript maintains the execution context through the data structure of the stack, the global execution context is at the bottom of the stack, and when a function is executed, the newly created function execution context is pressed into the stack, the execution context pointer points to the top of the stack, and the running code obtains the execution context of the currently executing function binding If the function body executes a nested function, it also creates an execution context and presses the stack, the pointer to the top of the stack, and when the nested function finishes, the execution context to which it is bound is pushed out, and the pointer again points to the execution context of the function binding. Similarly, the function finishes, and the pointer points to the global execution context.

The execution context can describe a data structure that contains variable objects (corresponding to global)/active objects (corresponding functions), scope chains, and this. When a function executes, the active object is created and bound to the execution context. The active object includes the variables, functions, arguments, etc. declared in the function body. The scope chain is constructed in the previous section and mentioned in terms of lexical scopes. Note that this is not part of the active object, and is determined at the moment the function executes.
The execution context is created in a specific sequence and stage, with different phases in different states, with specific details that can be looked at for reference and listed at the end.

Closed Bag

Knowing the scope chain and the execution context, looking back at the first piece of code, you can basically explain how the closure works. The execution context created by the function call and the information required by the lexical scope chain to hold the function call can only be returned to the local scope after the F function call.

It is important to note that multiple functions defined within a function use the same scope chain, and the scenario of assigning anonymous function objects using a For loop is more likely to cause errors, as follows:

var arr = [];
for (var i = 0; i < i++) {
Arr[i] = {
func:function () {return
i;}}
;
}
Arr[0].func (); Return 10 instead of 0

Arr[0].func () returns 10 instead of 0, which is biased with sensory semantics. Before ECMAScript 6 introduces let, the variable scope is within the entire function body, not in the code block, so all the defined Func functions in the above example refer to the same scope chain after the for loop, the value of I has changed to 10.

The right approach is this:

var arr = [];
for (var i = 0; i < i++) {
Arr[i] = {
Func:getfunc (i)
};
}
function Getfunc (i) {return
function () {return
i;
}
}
Arr[0].func (); return 0

The above content has introduced the JavaScript scope chain, the execution context and the closure related knowledge, hoped to be helpful to everybody.

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.