JS Scope and scope chain

Source: Internet
Author: User
Tags variable scope

has been a bit confused on the scope of JS, today by chance to read JavaScript authoritative guide, immediately be attracted to, write really good. I look at the sixth version, quite thick, about 1000 pages, JS Broad and profound, to be familiar with the need to master the great perseverance of Kung Fu.

One: function scope

Let's look at a short piece of code:

[JavaScript]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. var scope="global";
    2. function T () {
    3. Console.log (scope);
    4. var scope="local"
    5. Console.log (scope);
    6. }
    7. T ();

(PS:console.log () is the debugging tool provided by Firebug, very easy to use, interested in children's shoes can be used, than the browser +alert more useful)

The first sentence output is: "Undefined", not "global"

The second output is: "Local"

You might think that the first sentence will output: "Global" because the code has not executed var scope= "local", so it will definitely output "global".

I said the idea was absolutely right, just using the wrong object. We will first distinguish between the function scope of JavaScript and the block-level scope of our well-known C + +.

In C + +, each piece of code inside the curly braces has its own scope, and the variables are not visible outside the code snippet that declares them. JavaScript does not have a block-level scope at all, but a function scope.

The so-called function scope is to say that the variables are defined in the body of the function in which they are declared and in any function in which the body of the function is nested.

So according to the meaning of the function scope, the above code can be rewritten as follows:

[JavaScript]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. var scope="global";
    2. function T () {
    3. var scope;
    4. Console.log (scope);
    5. scope="Local"
    6. Console.log (scope);
    7. }
    8. T ();

As we can see, because of the function scope, local variables are always defined by the whole function body, we can declare the variable "advance" to the top of the function body, and the variable initialization is still in the original position.

Why JS does not have block-level scope, there is the following code for proof:

[JavaScript]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. var name="global";
    2. if (true) {
    3. var name="local";
    4. Console.log (name)
    5. }
    6. Console.log (name);

All output is "local", if there is a block-level scope, the obvious if statement will create a local variable name, and will not modify the global name, but there is no such, so JS does not have block-level scope.

Now it's good to understand why you can get that result. The scope declaration overrides the global scope but has not yet been assigned, so the output: "Undefined".

So the following code is very well understood.

[JavaScript]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. function T (flag) {
    2. if (flag) {
    3. var s="Ifscope";
    4. For (var i=0;i<2;i++)
    5. ;
    6. }
    7. Console.log (i);
    8. Console.log (s);
    9. }
    10. T (true);

Output: 2 "Ifscope"


Two: Variable scope

Or first look at a piece of code:

[JavaScript]View PlainCopy
    1. function T (flag) {
    2. if (flag) {
    3. s="Ifscope";
    4. For (var i=0;i<2;i++)
    5. ;
    6. }
    7. Console.log (i);
    8. }
    9. T (true);
    10. Console.log (s);


Is the above, the knowledge will declare s in the Var removed.

Will the program error or output "Ifscope"?

Let me uncover the answer, it will output: "Ifscope"

This is mainly a variable that is not declared with Var in JS is a global variable, and is the property of the top-level object.

So you use Console.log (WINDOW.S) will also output "ifconfig"

When declaring a variable with VAR, the property created is not configurable, that is, the delete operator cannot be removed

var name=1-No Delete

Sex= "Girl" to delete

THIS.AGE=22-To-remove

Three: Scope chain

Take a look at the code first:

[JavaScript]View PlainCopy
  1. Name="Lwy";
  2. function T () {
  3. var name="Tlwy";
  4. function S () {
  5. var name="Slwy";
  6. Console.log (name);
  7. }
  8. function ss () {
  9. Console.log (name);
  10. }
  11. S ();
  12. SS ();
  13. }
  14. T ();


When you execute S, the execution environment (the calling object) of the function S is created, the object is placed at the beginning of the list, and then the calling object of the function T is linked after, and finally, the global object. Then looking for the variable name from the beginning of the list, it's obvious

Name is "Slwy".

But when the SS () is executed, the scope chain is: SS ()->t ()->window, so name is "Tlwy"

Here's an example that's easy to make a mistake:

[HTML]View PlainCopy
  1. <html>
  2. <head>
  3. <script type="Text/javascript">
  4. function Buttoninit () {
  5. for (Var i=1;i<4;i++) {
  6. var b=document.getElementById ("button" +i);
  7. B.addeventlistener ("click", Function () {Alert ("button" +i);},false);
  8. }
  9. }
  10. window.onload=Buttoninit;
  11. </Script>
  12. </head>
  13. <body>
  14. <button id="button1">button1</button>
  15. <button id="Button2">button2</button>
  16. <button id="Button3">button3</button>
  17. </body>
  18. </html>

When the document is loaded and a few buttons register the click event, what will pop up when we click the button?

It's easy to make a mistake, yes, three buttons all pop up: "Button4", are you correct?

When the registration event ends, the value of I is 4, and when the button is clicked, the event function is functions () {Alert ("button" +i);} This anonymous function does not have I, according to the scope chain, so to find in the Buttoninit function, when I is the value of 4,

So pop up "Button4".

Four: With statement

When it comes to scope chains, you have to say with statements. The WITH statement is primarily used to temporarily extend the scope chain, adding objects in the statement to the scope's head.

Look at the code below

[JavaScript]View PlainCopy < param name= "wmode" value= "Transparent" >
    1. Person={name:"YHB", Age:22,height:175,wife:{name:"Lwy", age:21}};
    2. With (Person.wife) {
    3. Console.log (name);
    4. }

The WITH statement adds Person.wife to the head of the current scope chain, so the output is: "Lwy".

After the WITH statement ends, the scope chain returns to normal.

JS Scope and 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.