JavaScript scopes and scope chains

Source: Internet
Author: User

Each programming language has a valid range of variables, beyond which the variable is invalidated, which is the scope of the variable. From a mathematical point of view, it is the domain of the independent variable.

Scope is the accessible scope of a variable, that is, the scope controls the visibility and life cycle of variables and functions. In JavaScript, objects and functions are also variables, and variables are defined inside any function body that declares their function body and is nested within the body of the function.

Static scope and dynamic scope static scope

The scope of a declaration is defined by the program body at compile time, also known as the lexical scope. Most modern programming languages use static scope rules, which is the scope that JavaScript uses.
In a static-scoped language, the basic is the most nested scope rule: An identifier introduced by a declaration is visible in the scope of the declaration, and is visible within each scope within which it is nested, unless it is obscured by another declaration of the same name identifier nested inside.
In order to find the object referenced by a given identifier, it should be found in the current most-scoped scope. If a declaration is found, the object referenced by the identifier can be found. Otherwise we go to the immediate outer scope and continue to check the outer scope outward sequentially until we reach the outermost nesting level of the program, which is the scope of the global object declaration. If the declaration is not found at all levels, then the program has an error. As follows:

function cha () {    var name = "Xiao;"    function ChB () {        function  chc () {            console.log (name);   }}}
      first, the function searches for the definition of name from ChB (), and then continues a layer-by-layer search, finally searching for the definition of name in Cha () and an error if not found.
Dynamic scopes

In a dynamic-scoped language, the object referenced by a variable in a program is determined by the program's control flow information at the time the program runs.

Scope of JavaScript

There are two scopes in JavaScript, the global scope and the local scope, respectively.

1 scope (global scope)

Any location in the code is defined. Even if a global variable is defined in a section of JS code nested within an HTML page, the variable can still be accessed in the referenced JS file. This is likely to lead to global variable pollution.

Variables in the following three cases are considered global variables
(1) The outermost function and the outermost variable have global scope
(2) Variables that are directly assigned without definition are automatically declared as having global scope
(3) All Window object properties have global scope

2. Local scope local scope can only be accessed in a fixed code fragment, such as a variable inside a function (function scope)
varName = "Xuxiaoping";functionEchoname () {varFirstName = "Xu";//Local ScopeSecondname = "Xiao";//Global Scope    functionEchofirstname () {console.log (first name);//Xu} console.log (Secondname); returnEchofirstname;} Console.log (name);//Global Scopevarf =echoname (); F (); Console.log (firstname); Console.log (secondname); Result: Xuxiaopingxiaoxu//the inner layer function can access the variables of the outer functionundenfined//cannot access the internal variables of a function outside the functionXiao
      JavaScript attaches a global variable to the Window object and becomes the property of the Window object.
3. Function scope

Block-level scope: Any set of statements in a pair of curly braces belongs to a block, and all variables defined in it are not visible outside the code block. Most Class C languages have a block-level scope.
However, one important feature of JavaScript is that there is no block-level scope.

function Echoi () {    for (var i = 0;i<10;i++) {        ;  // Console.log (i);     }    if(true) {        var str = "Hello";    }    Console.log (i);    Console.log (str);} Echoi (); the output is:ten          Hello
        visible, the variable I defined in the block can still be accessed outside the For statement (or If,while). In other words, JavaScript does not support block-level scopes, it supports only function scopes, and variables defined anywhere in a function are visible anywhere in the function. As a one-start program, learn to learn C and

Java

      people, this is a bit difficult to adapt. As far as I test PHP, so too.

Of course, you can use the characteristics of JavaScript closures to simulate block-level scopes

function Echoi () {    (function() {        for (var i = 0;i<10;i++) {            ;  // Console.log (i);         }    })();     if (true) {        var str = "Hello";    }    Console.log (i);    Console.log (str);} Echoi (); The result is: I undefined
      this isolates the definition of the variable. In JS, in order to prevent naming conflicts, we should try to avoid using global variables and global functions, so the closure of the use of more special.
4. JavaScript Variable life cycle

The JavaScript variable life cycle is initialized when it declares.
Local variables are destroyed after the function has finished executing.
Global variables are destroyed after the page is closed.

The scope chain of JavaScript

A look is a chain, and probably can be combined with the linked list in the data structure.
Here I directly quoted an analysis of the particularly good article, suggested to see the original text, the original link is: http://www.cnblogs.com/lhb25/archive/2011/09/06/javascript-scope-chain.html

In JavaScript, functions are objects, and in fact, everything in JavaScript is an object. function objects, like other objects, have properties that can be accessed through code and a series of internal properties that are accessible only by the JavaScript engine. One of the internal properties is [[Scope]], defined by the ECMA-262 Standard third edition, which contains a collection of objects in the scope of the function being created, called the scope chain of the function, which determines which data can be accessed by the function.

When a function is created, its scope chain is populated with data objects that can be accessed by creating the scope of this function. For example, define a function such as the following:

function Add (num1,num2) {    var sum = num1 + num2;     return sum;}

When the function add is created, it fills a global object in its scope chain, which contains all the global variables, as shown (note: The picture shows only a subset of all variables):

The scope of the function add will be used at execution time. For example, execute the following code:

var total = Add (5,10);

Executing this function creates an internal object called the runtime context (execution context), which defines the environment at which the function executes. Each run-time context has its own scope chain, which is used for identifier resolution, when the runtime context is created, and its scope chain is initialized to the object contained by [[Scope]] of the currently running function.

These values are copied into the scope chain of the run-time context, in the order in which they appear in the function. Together they form a new object called the "Activation Object", which contains all the local variables, named arguments, parameter sets, and this of the function, which is then pushed into the front of the scope chain, and the active object is destroyed when the run-time context is destroyed. The new scope chain is as follows:

During the execution of a function, each time a variable is encountered, it undergoes an identifier parsing process to determine where to get and store the data. The process from the scope chain head, that is, starting from the active object search, find an identifier of the same name, if found to use this identifier corresponding to the variable, if not found to continue to search the scope chain of the next object, if the search all objects are not found, the identifier is considered undefined. Each identifier undergoes such a search process during the execution of the function.

Scope Chain and code optimization

As you can see from the structure of the scope chain, the deeper the identifier is in the scope chain of the run-time context, the slower the read and write speed will be. As shown, because global variables always exist at the end of the run-time context chain, finding global variables is the slowest when identifiers are resolved. Therefore, when writing code, you should use as few global variables as possible, using local variables as much as you can. A good rule of thumb is that if a cross-scope object is referenced more than once, it is stored in a local variable before it is used. For example, the following code:

function ChangeColor () {document.getElementById ("Btnchange"). onclick=function() {        document.getElementById ("Targetcanvas"). style.backgroundcolor= "Red";    };}

This code is simple and will not show a huge performance boost after rewriting, but if there are a large number of global variables in the program that are accessed from time to time, the rewritten code performance can be significantly improved.

With change scope chain

The runtime context for each execution is unique, so calling the same function multiple times will result in multiple runtime contexts being created, and the execution context will be destroyed when the function finishes executing. Each run-time context is associated with a scope chain. In general, the scope chain is only affected by the WITH statement and catch statement during the run-time context.

The WITH statement is a quick way to apply an object to avoid writing duplicate code. For example:

function Initui () {    with(document) {        var bd=Body,            links= getElementsByTagName ("a"),            i=0,            len=links.length;          while (I < len) {            update (links[i+ +]);        }        getElementById ("Btninit"). onclick=function() {            dosomething ();}        ;}    }
      using the width statement here to avoid writing the document multiple times seems more efficient and actually creates performance problems.

When the code runs to the WITH statement, the scope chain of the run-time context is temporarily changed. A new Mutable object is created that contains all the properties of the object specified by the parameter. This object will be pushed into the head of the scope chain, which means that all local variables of the function are now in the second scope chain object, so the access cost is higher. As shown in the following:

Therefore, you should avoid using the WITH statement in your program, in which case you can improve performance by simply storing the document in a local variable.

Summarize

1, the scope of the variable is the scope of the variable is valid.
2. The scope chain of a variable is the collection of objects in the scope that is created.

JavaScript scopes and scope chains

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.