JavaScript scope chain Use introduction _javascript tips

Source: Internet
Author: User
Tags closure

Before writing a JavaScript closure is what the article understanding closure, feel written very clearly, you can simply understand the cause of closure, but see comments are said to understand the scope chain and active objects to really understand the closure, initially dismissed, Later, when interacting with colleagues in the company, I found that the scope and execution environment was really important and basic and helpful in understanding JavaScript closures, so write an understanding of the scope and execution environment.

Scope

Scopes are the accessible scope of variables and functions, controlling the visibility and lifecycle of variables and functions, and the scope of variables in JavaScript has global scope and local scope.

The simple JavaScript scope is well understood, in some Class C programming language, each piece of code within the curly braces has its own scope, and the variables are invisible outside the code snippet that declares them, called block-level scopes, where JavaScript is easy for beginners to misunderstand. JavaScript does not have a block and scope, only function-level scopes: variables are visible within the function body in which they are declared and their child functions.

A variable is not declared or declared within a function without VAR is a global variable, has global scope, all properties of the Window object have global scope, and can be accessed anywhere in the code, and variables that are declared within the function and modified as Var are local variables that can only be used in the function body. The parameter of the function, although not using Var, is still a local variable.

Copy Code code as follows:

var a=3; Global variables
function fn (b) {//local variable
c=2; Global variables
var d=5; Local variables
function Subfn () {
var E=d; The local variable of the parent function is visible to the child function
for (Var i=0;i<3;i++) {
Console.Write (i);
}
alert (i);//3, declared inside a for loop, still visible within the loop outer function, no block scope
}
}
alert (c); Declared within a function but without the Var modifier, is still a global variable

As long as it is understood that JavaScript does not have a block scope, simple JavaScript scopes are well understood, and there is a bit easier to confuse beginners with JavaScript variables that can function and parse or declare ahead of time, but say something JavaScript, although interpreted as execution, is not step-by-step interpretation of execution, and before the actual interpretation of execution, the JavaScript interpreter parses the code and interprets the variable, the function declaration part in advance. This means that we can invoke function before the function declaration statement, which most people get used to, but it's very strange to parse a variable at first glance.

Copy Code code as follows:

Console.log (a); Undefined
var a=3;
Console.log (a); 3
Console.log (b); Uncaught REFERENCEERROR:B is not defined

The above code is executed before the Var a=3; The declaration section has been resolved (but will not execute the assignment statement), so the first time will be undefined without an error, the execution of the assignment statement will get 3, the previous code to remove the last sentence and the following code is the same effect.
Copy Code code as follows:

var A;
Console.log (a); Undefined
A=3;
Console.log (a); 3

However
If this is the case, the JavaScript scope problem is simple, but because of the problems caused by the function's child function, the scope is not so simple. Big shot--execution environment or runtime context (good turtle): The Execution Environment (execution) defines other data that a variable or function has access to, and determines their behavior. Each execution environment has an associated variable object (variable object, VO), and all variables and functions defined in the execution environment are stored in this object, and the parser accesses the internal object as it processes the data.

The global execution environment is the outermost execution environment in which the global execution environment is a window object, so all global variables and functions are created as properties and magnification of the Window object. Each function has its own execution environment, when the execution stream enters a function, the environment of the function is pushed into a stack of functions, and the execution of the environment is destroyed after the function has been executed, and all the variables and function definitions stored therein are destroyed, and control is returned to the previous execution environment. The global execution environment is destroyed when the application exits (browser shutdown).

Scope chain

When code executes in an environment, a scope chain (scope chain, not called SC) of variable objects is created to ensure orderly access to variables and functions that the execution environment has access to. Scope The first object is always the variable object (VO) in the environment where the code is currently executing

Copy Code code as follows:

function A (x,y) {
var b=x+y;
return b;
}


When function A is created, its scope chain fills the global object, and all global variables are in the global object

If the execution environment is a function, its active object (Activation object, AO) is the first object in the scope chain, the second object is the containing environment, and the next is the containing environment containing the environment ....

Copy Code code as follows:

function A (x,y) {
var b=x+y;
return b;
}
var tatal=a (5,10);

At this time var total=a (5,10), the scope chain of the statement is as follows

In the function of the operation of the identifier is the process of searching along the scope chain, starting from the first object, step backwards back, until you find the identifier with the same name, found no longer continue to traverse, can not find the error.

Let's take a look at the closure.

Previously, blogs have concluded that JavaScript needs to retain the referenced function as long as there is a possibility of calling internal functions. and the JavaScript runtime needs to track all the variables that refer to the internal function until the last variable is discarded, and the JavaScript garbage collector frees up the appropriate memory space. Look back. A lot of understanding, the variables defined by the parent function in the scope chain of the child function, the child function is not destroyed, and all variables and functions in the scope chain are maintained and will not be destroyed.

Copy Code code as follows:

for (Var i=0;i<elements.length;i++) {
Elements[i].onclick=function () {
alert (i);
}
}

This is the classic error mentioned in the previous blog, where element click Alert is length, which is the scope chain for element-bound Click event handlers in this code

Because the intrinsic function (the Click event handler is possible at all times), its scope chain cannot be destroyed (not to mention that in this example I in the global scope, only page unload is destroyed), the value of I keeps the length value of the For loop after execution, So every time you trigger the onclick, alert length is not.

Copy Code code as follows:

for (Var i=0;i<elements.length;i++) {
(function (n) {
Elements[n].onclick=function () {
alert (n);
}
}) (i);
}

Why this is OK, at this time the onclick reference variable becomes n, and due to the immediate execution function, each onclick function maintains its corresponding n (0~length-1) in the scope chain, and this is OK.

At last

The

Actually understands the execution environment and the scope chain, and the closure turns into something obvious, but you can't abuse closures, as you can see from the example above, the closure causes the child function to keep all the variables and functions of its scope chain and memory, memory consumption is very large, in use when trying to destroy the parent function no longer used variables.

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.