The scope chain understanding of JS __js

Source: Internet
Author: User
Tags variable scope

Original article Source: http://blog.csdn.net/yueguanghaidao/article/details/9568071#comments



The scope of JS has been a bit confused, and today I accidentally read the JavaScript Authority Guide, was immediately attracted to write really good. I am looking at the sixth version, quite thick, probably more than 1000 pages, JS Broad and profound, to be familiar with the need to master the great perseverance great effort.

One: function scopes

Let's look at a short piece of code: [JavaScript] view plain copy print? var scope= "global"; function T () {Console.log (scope); var scope= "local" console.log (scope);} t ();

var scope= "global";
function T () {
    console.log (scope);
    var scope= "local"
    console.log (scope);
}
T ();

(PS:console.log () is firebug to provide debugging tools, very easy to use, interested in children's shoes can be used, than the browser +alert much better.

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

The second output is: "Local"

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

I said the idea was absolutely correct, but I used the wrong object. We first want to differentiate between the function scopes of JavaScript and the block-level scopes that we know about C + +, and so on.

In C + +, each piece of code within the curly braces has its own scope, and the variables are not visible outside the code snippet in which they are declared. JavaScript does not have a block-level scope, but a function scope.

The so-called function scope is to say:-The variables are defined in the body of the function that declares them and in any function that is nested within the function body.

So, depending on what the function scope means, you can rewrite the code as follows:

[JavaScript] view plain copy print? var scope= "global"; function T () {var scope; Console.log (scope); scope= "Local" console.log (scope);} t ();

var scope= "global";
function T () {
    var scope;
    Console.log (scope);
    Scope= "Local"
    console.log (scope);
T ();

We can see that, because of the function scope characteristic, the local variable is always defined by the whole function body, we can declare the variable "ahead" to the top of the function body, while the variable initialization is still in its original position.

Why say JS does not have block level scope, have the following code as proof:

[JavaScript] view plain copy print? var name= "global"; if (true) {var name= ' local '; Console.log (name)} console.log (name);

var name= "global";
if (true) {
    var name= ' local ';
    Console.log (name)
}
Console.log (name);
All output is "local", if there is a block-level scope, the apparent if statement will create the locals name, and will not modify the global name, but no, so JS has no block-level scope.

Now it's good to understand why it's going to come out like that. The scope declaration overrides the global scope, but has not yet been assigned, so the output is: "Undefined".

So the following code is very well understood.

[JavaScript] view plain copy print? function T (flag) {if (flag) {var s= "Ifscope"; for (var i=0;i<2;i++);} console.log (i); Console.log (s);} t (True);

function T (flag) {
    if (flag) {
        var s= "Ifscope";
        for (var i=0;i<2;i++) 
            ;
    }
    Console.log (i);
    Console.log (s);
}
T (TRUE);
Output: 2 "Ifscope"


Two: Variable scope

Or first look at a piece of code:

[JavaScript] view plain copy print? function T (flag) {if (flag) {s= "Ifscope"; for (var i=0;i<2;i++);} console.log (i);} t (True); Console.log (s);

function T (flag) {
    if (flag) {
        s= "ifscope";
        for (var i=0;i<2;i++) 
            ;
    }
    Console.log (i);
}
T (true);
Console.log (s);

Is the above version, the knowledge will declare the Var in S is removed.

The program will be an error or output "Ifscope" it.

Let me solve the riddle, will output: "Ifscope"

This is mainly JS in the VAR declared variables are global variables, but also the properties of the top-level object.

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


When you declare a variable with VAR, the property that you create is not configurable, that is, it cannot be deleted by the delete operator

var name=1-> cannot be deleted

sex= "Girl"-> can be deleted

This.age=22-> can be deleted


Three: Scope chain

Let's look at a piece of code:

[JavaScript] view plain copy print? Name= "Lwy"; function T () {var name= "Tlwy"; function s () {var name= "Slwy"; Console.log (name);} function ss () {Console.log (name);} s () ; SS (); } t ();

Name= "Lwy";
function T () {
    var name= "Tlwy";
    function S () {
        var name= "Slwy";
        Console.log (name);
    function SS () {
        console.log (name);
    }
    S ();
    SS ();
}
T ();

When S is executed, the execution environment (the calling object) of the function S is created, and the object is placed at the beginning of the list, and then the calling object of function T is linked to, and finally, the global object. And then looking at 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"

Let's look at an example that's easy to make a mistake:

[HTML] view plain copy print?

When the document is loaded, click on the button to register a few buttons, and when we click on the button, what prompts will pop up.

It's easy to make mistakes, yes, three buttons are pop-up: "Button4", are you correct?

When the registration event is over, the value of I is 4, and when the button is clicked, the event function () {Alert ("button" +i);} There is no I in this anonymous function, according to the scope chain, so go to the Buttoninit function, at which point I is a value of 4,

So Pop "Button4".


Four: With statement

When it comes to the scope chain, you have to say the WITH statement. The WITH statement is used primarily to temporarily extend the scope chain and add the objects in the statement to the head of the scope.

Look at the code below.
[JavaScript] view plain copy print? Person={name: "Yhb", Age:22,height:175,wife:{name: "Lwy", age:21}; With (Person.wife) {console.log (name);}

Person={name: "Yhb", Age:22,height:175,wife:{name: "Lwy", age:21};
With (Person.wife) {
    console.log (name);
}
The WITH statement adds Person.wife to the head of the current scope chain, so the output is: "Lwy".

After the With statement is finished, the scope chain returns to normal.


The scope of JS has been a bit confused, and today I accidentally read the JavaScript Authority Guide, was immediately attracted to write really good. I am looking at the sixth version, quite thick, probably more than 1000 pages, JS Broad and profound, to be familiar with the need to master the great perseverance great effort.

One: function scopes

Let's look at a short piece of code: [JavaScript] view plain copy print? var scope= "global"; function T () {Console.log (scope); var scope= "local" console.log (scope);} t ();

var scope= "global";
function T () {
    console.log (scope);
    var scope= "local"
    console.log (scope);
}
T ();

(PS:console.log () is firebug to provide debugging tools, very easy to use, interested in children's shoes can be used, than the browser +alert much better.

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

The second output is: "Local"

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

I said the idea was absolutely correct, but I used the wrong object. We first want to differentiate between the function scopes of JavaScript and the block-level scopes that we know about C + +, and so on.

In C + +, each piece of code within the curly braces has its own scope, and the variables are not visible outside the code snippet in which they are declared. JavaScript does not have a block-level scope, but a function scope.

The so-called function scope is to say:-The variables are defined in the body of the function that declares them and in any function that is nested within the function body.

So, depending on what the function scope means, you can rewrite the code as follows:

[JavaScript] view plain copy print? var scope= "global"; function T () {var scope; Console.log (scope); scope= "Local" console.log (scope);} t ();

var scope= "global";
function T () {
    var scope;
    Console.log (scope);
    Scope= "Local"
    console.log (scope);
T ();

We can see that, because of the function scope characteristic, the local variable is always defined by the whole function body, we can declare the variable "ahead" to the top of the function body, while the variable initialization is still in its original position.

Why say JS does not have block level scope, have the following code as proof:

[JavaScript] view plain copy print? var name= "global"; if (true) {var name= ' local '; Console.log (name)} console.log (name);

var name= "global";
if (true) {
    var name= ' local ';
    Console.log (name)
}
Console.log (name);
All output is "local", if there is a block-level scope, the apparent if statement will create the locals name, and will not modify the global name, but no, so JS has no block-level scope.

Now it's good to understand why it's going to come out like that. The scope declaration overrides the global scope, but has not yet been assigned, so the output is: "Undefined".

So the following code is very well understood.

[JavaScript] view plain copy print? function T (flag) {if (flag) {var s= "Ifscope"; for (var i=0;i<2;i++);} console.log (i); Console.log (s);} t (True);

function T (flag) {
    if (flag) {
        var s= "Ifscope";
        for (var i=0;i<2;i++) 
            ;
    }
    Console.log (i);
    Console.log (s);
}
T (TRUE);
Output: 2 "Ifscope"


Two: Variable scope

Or first look at a piece of code:

[JavaScript] view plain copy print? function T (flag) {if (flag) {s= "Ifscope"; for (var i=0;i<2;i++);} console.log (i);} t (True); Console.log (s);

function T (flag) {
    if (flag) {
        s= "ifscope";
        for (var i=0;i<2;i++) 
            ;
    }
    Console.log (i);
}
T (true);
Console.log (s);

Is the above version, the knowledge will declare the Var in S is removed.

The program will be an error or output "Ifscope" it.

Let me solve the riddle, will output: "Ifscope"

This is mainly JS in the VAR declared variables are global variables, but also the properties of the top-level object.

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


When you declare a variable with VAR, the property that you create is not configurable, that is, it cannot be deleted by the delete operator

var name=1-> cannot be deleted

sex= "Girl"-> can be deleted

This.age=22-> can be deleted


Three: Scope chain

Let's look at a piece of code:

[JavaScript] view plain copy print? Name= "Lwy"; function T () {var name= "Tlwy"; function s () {var name= "Slwy"; Console.log (name);} function ss () {Console.log (name);} s () ; SS (); } t ();

Name= "Lwy";
function T () {
    var name= "Tlwy";
    function S () {
        var name= "Slwy";
        Console.log (name);
    function SS () {
        console.log (name);
    }
    S ();
    SS ();
}
T ();

When S is executed, the execution environment (the calling object) of the function S is created, and the object is placed at the beginning of the list, and then the calling object of function T is linked to, and finally, the global object. And then looking at 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"

Let's look at an example that's easy to make a mistake:

[HTML] view plain copy print?

When the document is loaded, click on the button to register a few buttons, and when we click on the button, what prompts will pop up.

It's easy to make mistakes, yes, three buttons are pop-up: "Button4", are you correct?

When the registration event is over, the value of I is 4, and when the button is clicked, the event function () {Alert ("button" +i);} There is no I in this anonymous function, according to the scope chain, so go to the Buttoninit function, at which point I is a value of 4,

So Pop "Button4".


Four: With statement

When it comes to the scope chain, you have to say the WITH statement. The WITH statement is used primarily to temporarily extend the scope chain and add the objects in the statement to the head of the scope.

Look at the code below.
[JavaScript] view plain copy print? Person={name: "Yhb", Age:22,height:175,wife:{name: "Lwy", age:21}; With (Person.wife) {console.log (name);}

Person={name: "Yhb", Age:22,height:175,wife:{name: "Lwy", age:21};
With (Person.wife) {
    console.log (name);
}
The WITH statement adds Person.wife to the head of the current scope chain, so the output is: "Lwy".

After the With statement is finished, the scope chain returns to normal.


The scope of JS has been a bit confused, and today I accidentally read the JavaScript Authority Guide, was immediately attracted to write really good. I am looking at the sixth version, quite thick, probably more than 1000 pages, JS Broad and profound, to be familiar with the need to master the great perseverance great effort.

One: function scopes

Let's look at a short piece of code: [JavaScript] view plain copy print? var scope=

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.