The scope and scope chain of JS

Source: Internet
Author: User
Tags variable scope

The scope and scope chain of JavaScript. In the beginning of JavaScript, think it is no different from other languages, especially the scope of this piece, take for granted that "global variables are accessible anywhere in the program, that is, the variables written in the function, local variables are written inside the function or inside the loop body, The loop body and function are not accessible, but in JavaScript it is not so simple and requires deep learning.

I. What is a scope
Any programming language has the concept of scope, in a nutshell, scope is the scope of the variable and function accessibility. For example, C + +, etc., are block-level scope, that is, in each code block declared variables, out of this code block is not visible, and JS there is no block-level scope of the concept, but the function scope. As in the following example:

12345678910 function test () { &NBSP;&NBSP;&NBSP;&NBSP; var sum = 0; &NBSP;&NBSP;&NBSP;&NBSP; for (var i = 0; i < 2; i++) &NBSP;&NBSP;&NBSP;&NBSP; {          sum = sum Code class= "SQL plain" >+ i; &NBSP;&NBSP;&NBSP;&NBSP; } &NBSP;&NBSP;&NBSP;&NBSP; console.log (i); }  test ();

The above program output is 2, know C and C + + or Java will know that the variables defined in the For loop body block outside the loop body is inaccessible, but in JS, there is no concept of block scope, only the concept of function scope, so long as the function is defined within the body of the variable, is accessible within the body of the function.

Two. Function scope
See the small example above, you should have a little vague understanding of the function scope. In other words, variables and functions are accessible within the body of the function in which they are declared, and in any function body nested inside the function body. Let's look at a small example below:

1234567891011 function test(){    var name = "xiyangyang";    function showname(){        console.log(name);    }    showname();}test(); //xiayangyangshowname(); //ReferenceError: showname is not defined

Results such as comments after the code, visible variables and functions are valid only within the body of the currently running function, and are not valid outside the current running function body.

three. Variable scope
JS variable is special, here are some small examples, see its special point:
(1) Global variables are overwritten:

123456789 var name = " Huitaiyang "  function test () {       console.log ( name &NBSP;&NBSP;&NBSP;&NBSP; var name = "Xiyangyang" &NBSP;&NBSP;&NBSP;&NBSP; console.log ( name }  test ();

If the code does not know the JS variable scope of the affirmation will feel that the first output "Huitaiyang", the second output "Xiyangyang", actually not, the first will output "undefined", the second is "Xiyangyang" (In fact, I think so at the beginning), anyway, please keep in mind that JS is a function scope, that is, it will first look inside the function of the Name property, can not find to continue to look up to the previous layer.
In this small example, there is the definition of name inside the test function, which is found, it will not be looking for the upper layer, but the name is not assigned at the time of printing, so the output of the undefined, the second time the printing has been assigned value, is the normal "Xiyangyang".

(2) A local variable without a VAR declaration rises to a global variable:

1234567 functiontest(){    name = "xiyangyang";    console.log(name);}test();console.log(name);

The above code two printing results are "Xiyangyang", so no var declared variables are global variables, is the property of the Window object, Console.log (name); This is consistent with the results above.

Four. Scope chain
Once the function is created, the scope of the function is determined, and the scope chain is made up of the collection of objects in the scope. When the function executes, it places all variables within the currently executing function (including this) at the header of the scope chain, placing the object outside the function in the second, third ... Layer, the Window object is placed at the outermost level. The number of layers in the scope chain is related to the number of layers of the function.

12345678910111213141516 var name = "huitaiyang"function test(){    var name = "xiyangyang";    function show1(){        var name = "lanyangyang";        console.log(name);    }    function show2(){        console.log(name);    }    show1();    show2();}test();

In the example above, the printed results are "Langyangyang" and "Xiyangyang".
Parse: When test () is executed, run to Show1, create the Show1 execution environment, place all the internal variables of Show1 in the scope chain header, and then place all objects of the function test behind Show1, and finally the Window object. The Name property is then started from the head of the scope chain, so the scope chain for Show1 () is: Show1 ()->test ()->window
, so name is Lanyangyang; the scope chain of Show2 () is: Show2 ()->test ()->window
, so name is Xiyangyang.

Five. Scope Chain and code optimization
After reading all of the above the students will be very easy to understand here, the following small example:

12345 function changecolor () {      document.getelementbyid ( ' btn ' ). onclick = function () { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; document.getelementbyid ( ' red ' &NBSP;&NBSP;&NBSP;&NBSP;

Everyone knows that document is a global variable, that is, at the end of the scope chain, the lookup is very resource-intensive, so it needs to be optimized and the code is:

123456 function changecolor () { &NBSP;&NBSP;&NBSP;&NBSP; var doc = document; &NBSP;&NBSP;&NBSP;&NBSP; doc.getelementbyid ( ' btn ' ). onclick = function () { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; doc.getelementbyid ( ' red ' &NBSP;&NBSP;&NBSP;&NBSP;

It's enough to look at it once, so when an object is accessed across scopes, it can be stored as a local variable, which is what makes the optimization work.

Six. Modifying the scope chain
Here is a simple mention, can understand the good, with and catch will modify the scope of the function chain.
(1) If there is a with in the code block, all objects in the with are placed at the top of the current scope chain, and the current function is placed on the second level. Will degrade the performance of the code, so it is not recommended.
(2) The Catch statement places the exception object at the top of the scope chain, and the current execution function is placed on the second level. Also affects the performance of the code.

The scope and scope chain of JS

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.