JavaScript scope chain

Source: Internet
Author: User

Before writing a JavaScript closure what exactly is the article understanding closures, feel written clearly, can simply understand the cause of closures, but look at the comments are said to understand the scope chain and the active object in order to really understand the closure, initially dismissed, Later, when communicating with colleagues in the company, it is really important and fundamental to understand the scope and execution environment, which is helpful for understanding JavaScript closures, so write an understanding of the scope and execution environment.

Scope

Scope is the accessible scope of variables and functions, controlling the visibility and life cycle of variables and functions, and the scope of variables in JavaScript is global scope and local scope.

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

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

var a=3; Global variable            function fn (b) {//local variable                c=2;//global variable                var d=5;//local variable                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 within a for loop, is still visible within the loop outer function, without block                scope            }            alert (c);//declaration within a function without var decoration, still a global variable

As long as you understand that JavaScript does not have a block scope, a simple JavaScript scope is well understood, and a little bit easier for beginners to confuse is the JavaScript variable function and parsing or declaration ahead of time, a lot of names but said is one thing, Although JavaScript is an explanation of execution, it is not a step-by-line explanation of execution, before the actual interpretation of execution, the JavaScript interpreter pre-parses the code, the variables, function declarations part of the early interpretation, This means that we can call function before the function declaration statement, which most people take for granted, but it would be strange at first glance for a variable to be parsed.

Console.log (a); Undefined            var a=3;            Console.log (a); 3            Console.log (b);//uncaught referenceerror:b is not defined

The above code is var a=3 before execution; The declaration part has been pre-parsed (but will not execute the assignment statement), so the first time will be undefined without error, after executing the assignment statement will get 3, the previous code to remove the last sentence and the following code is the same effect.

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

If this is the case, then the JavaScript scope problem is simple, but the problem caused by the function sub-function makes the scope more simple. Big shots-execution environment or run-time context (good turtle): The Execution Environment (execution context) defines the other data that variables or functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it (variable object, VO), and all variables and functions defined in the execution environment are stored in the object, and the parser accesses the internal object when it processes the data.

The global execution environment is the outermost execution environment, where the global execution environment is the 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, and when the execution flow enters a function, the environment of the function is pushed into a function stack, and after the function is executed, the environment is executed and destroyed, all the variables and function definitions are destroyed, and control is returned to the previous execution environment. The global execution environment will not be destroyed until the application exits (browser close).

Scope chain

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

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

When function A is created, its scope chain fills in global objects, and global objects have all global variables

If the execution environment is a function, then its active object (Activation object, AO) acts as the first object of the scope chain, the second object is the containing environment, and the next is the containing environment that contains the environment ....

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

The parsing of identifiers during function runs is the process of searching at the first level of the scope chain, starting with the initial object, and backtracking backwards until the identifier of the same name is found, and no further traversal is found, and an error is not found.

Let's take a look at the closures.

Previous blogs have concluded that JavaScript needs to preserve the referenced function as long as there is the possibility of invoking an intrinsic function. and the JavaScript runtime needs to keep track of all the variables that reference this intrinsic 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 parent function defines a variable in the scope chain of a child function, the child function is not destroyed, and all variables and functions in its scope chain are maintained and will not be destroyed.

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

This is the classic error mentioned in the previous blog, each element click Alert is length, this code is bound to the element of the Click event handler scope chain is like this

Because the internal function (the Click event handler is called at any time), its scope chain cannot be destroyed (let alone in this case I in the global scope, only the page unload is destroyed), the value of I will keep the for loop after the execution of the length value, So each time the onclick is triggered, the alert length is not.

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

Why is this, when the onclick reference variable becomes n, and because of the reason for executing the function immediately, each onclick function maintains the corresponding n (0~length-1) in the scope chain, which is then possible.

At last

In fact, after the implementation of the environment and the scope chain, the closure turned into obvious things, but also can not abuse closure, from the above example, the closure will make the child function to maintain its scope chain of all variables and functions and memory, memory consumption is very large, when used to try to destroy the parent function is no longer used variables.

JavaScript scope chain

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.