Talk about JavaScript scope and scope Chain _ basics

Source: Internet
Author: User
Tags closure

Each programming language, its variables have a certain range of valid, beyond this range, the variable is invalid, which is the scope of the variable. From the point of view of mathematics, it is the field of the independent variable.

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

First, static scope and dynamic scope

Static scope

Refers to a declared scope that is determined by the program body at compile time, also known as a lexical scope. Most modern programming languages use static scope rules, and JavaScript is the scope of this application.
In a static-scoped language, basically, the most nested scope rule: An identifier introduced by a declaration is visible within the scope of the declaration in which it resides, and is visible within each scope within which it is nested, unless it is masked by another declaration of an identifier with the same name nested inside it.
In order to find the object referenced by a given identifier, it should be found in the current top-level scope. If a declaration is found, the object referenced by the identifier can also be found. Otherwise, we look in the immediate outer scope and continue to examine the outer scope in order, 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 goes on to the top level of the search, and finally the definition of name is found in Cha (), and if it is not found, an error is made.

2. Dynamic scopes

In the language of a dynamic scope, the object referenced by a variable in a program is determined by the control flow information of the program at the time the program is run.

Second. Scope of JavaScript

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

1. Global scope

Any location in your code is defined. Even if a global variable is defined in a paragraph of JS code nested in an HTML page, the variable is still accessible in the referenced JS file. This is likely to cause global variable pollution.

The following three variables are treated as global variables
(1) The outermost function and the outermost variable have global scope
(2) undefined and directly assigned variables are automatically declared to have global scope
(3) Properties of all window objects have global scope

2. Local scope (area scope)

Local scopes can generally only be accessed in a fixed code fragment, such as a variable within a function (function scope)

var name = "Xuxiaoping";
function Echoname () {
 var firstname = "Xu";/local scope
 secondname = "Xiao";/global scope function
 Echofirstname () { C10/>console.log (name);//xu
 console.log (secondname);
 return echofirstname;
Console.log (name);//global scope

var f = echoname ();
f ();
Console.log (firstname);
Console.log (Secondname);

The results are:
xu//inner function can access variables of outer function
undenfined//cannot access internal variables of functions outside function

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, in which all the variables defined are not visible outside the code block. Most Class C languages have block-level scopes.
One important feature of JavaScript, however, 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 results are:


Visible, the variable I defined in the block is still accessible, outside of the for statement (and can be if,while). That is, JavaScript does not support block-level scopes, it only supports function scopes, and variables defined anywhere in a function are visible anywhere in the function. This is a bit difficult to adapt as a person who learns to learn C and Java at the beginning of programming. As far as I'm testing PHP, so is it.

Of course, you can simulate a block-level scope using JavaScript's closure characteristics.

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 this closure is used more particularly.

4. JavaScript Variable life cycle

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

Third. The scope chain of JavaScript

A look is a chain, probably can be with the data structure of the linked list in combination

In JavaScript, a function is also an object, 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 to the JavaScript engine. One of the internal properties is [[Scope]], defined by the third edition of the ECMA-262 Standard, which contains a collection of objects in the scope of the function being created, which is 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 are accessible in the scope of this function creation. 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, its scope chain fills in a global object that contains all the global variables, as shown in the following illustration (note: The picture illustrates only a subset of the variables):

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

var total = Add (5,10);

When this function is executed, an internal object called the Run-time context (execution contexts) is created, and the runtime context defines the environment at which the function executes. Each run-time context has its own scope chain, used for identifier resolution, when the runtime context is created, and its scope chain is initialized to the object contained in the current running function's [[Scope]].

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 active object (Activation object), which contains all the local variables of the function, named arguments, a collection of parameters, and this, and then this object is pushed into the front of the scope chain, and the active object is destroyed when the runtime context is destroyed. The new scope chain is shown in the following illustration:

During function execution, each time a variable is encountered, an identifier parsing process is experienced to determine where to get and store the data. The process from the scope chain head, that is, from the active object search, look for an identifier with the same name, if found to use the variable corresponding to this identifier, if you do not find the next object in the scope chain continues to search, if all objects are not found, the identifier is not defined. During function execution, each identifier undergoes such a search process.

Fourth. scope chain and code optimization

It can be seen from the structure of the scope chain that the deeper the identifier is in the scope chain of the runtime context, the slower the read and write speed will be. As shown in the figure above, because global variables always exist at the very end of the run-time context-scoped chain, finding global variables is the slowest when identifiers are parsed. So, when writing code, you should use as little global variables as possible, and use local variables whenever you can. A good rule of thumb is that if a cross scoped object is referenced more than once, it is stored in a local variable for reuse. For example, the following code:

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

This function refers to a two-time global variable document, which must traverse the entire scope chain until it is finally found in the global object. This code can be rewritten as follows:

function ChangeColor () {
 var doc=document;
 Doc.getelementbyid ("Btnchange"). Onclick=function () {
 Doc.getelementbyid ("Targetcanvas"). Style.backgroundcolor= "Red";}

This code is simpler and will not show a significant performance boost when overridden, but if a large number of global variables are accessed from time to time in the program, the rewritten code performance can improve significantly.

Fifth. With the change of scope chain

The corresponding run-time context for each execution is unique, so multiple calls to the same function can result in the creation of multiple run-time contexts, and the execution context is destroyed when the function completes. Each run-time context is associated with a scope chain. In general, the scope chain is only affected by the WITH statement and catch statements during runtime contexts.

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

function Initui () {with
 (document) {
 var bd=body,
 links=getelementsbytagname ("a"),
 len= Links.length;
 while (I < len) {
 update (links[i++]);
 getElementById ("Btninit"). Onclick=function () {
 dosomething ();}

Using the width statement to avoid writing the document multiple times, it looks more efficient and actually creates a performance problem.

When the code runs to the WITH statement, the scope chain of the runtime 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 to 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 costs are higher. As shown in the following illustration:

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


1. The scope of the variable is the range in which the variable is valid.
2. The scope chain of a variable is the set of objects that are created in the scope.

The above is the entire content of this article, I hope to learn JavaScript program to help you.

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: 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.