On the scope chain of JS (Ii.)

Source: Internet
Author: User

The previous article describes three important parts of execution context: Vo/ao,scope chain and this, and details Vo/ao's performance in JavaScript code execution.

This article looks at the scope chain in execution context.

Scope

Before you start introducing the scope chain, look at the scope (scope) in JavaScript. In many languages (C++,c#,java), scopes are determined by code blocks (code that is wrapped by {}), but in JavaScript scopes it is related to a function, or it can be described as function-based.

For example, the variable "I" can still be accessed after the code block for the for loop ends.

12345 for(var i = 0; i < 3; i++){    console.log(i);}console.log(i); //3

For scopes, they can be divided into global scope and local scope (local Scpoe).

Objects in the global scope can be accessed anywhere in the code, and in general, objects in the following situations are in the global scope:

    • The outermost function and the variables defined outside the outermost function
    • Variables not declared by the keyword "var"
    • The properties of the Window object in the browser

A local scope is also called a function scope, and all variables and functions can only be used within the scope.

123456789 var foo = 1;window.bar = 2;function baz(){    a = 3;    var b = 4;}// Global scope: foo, bar, baz, a// Local scope: b
Scope chain

As you can see in the previous article, there is a VO in each execution context that holds information such as variables, functions, and parameters.

In the JavaScript code run, all the variables used need to go to the current ao/vo to find, when not found, will continue to find the upper execution context Ao/vo. The process of looking up a level up is that all ao/vo in execution context makes up a chain of scopes.

Therefore, the scope chain is related to an execution context and is a list of all variable objects (including parent variable objects) in the internal context for variable queries.

Scope = Vo/ao + all Parent Vo/aos

See an example:

123456789101112131415 var x = 10;function foo() {    var y = 20;         function bar() {        var z = 30;               console.log(x + y + z);    };        bar()};foo();

The output of the above code is "60", and the function bar can access "Z" directly, and then access the upper "X" and "Y" through the scope chain.

    • Green Arrow pointing to Vo/ao
    • Blue arrow pointing to Scope chain (Vo/ao + all Parent Vo/aos)

Let's look at a more typical example:

12345678910 var data = [];for(var i = 0; i < 3; i++){    data[i]=function() {        console.log(i);    }}data[0]();// 3data[1]();// 3data[2]();// 3

The first sensation (illusion) This code will output "0,1,2". However, according to the previous introduction, the variable "i" is a variable stored in "Global Vo", the value of "I" is set to 3 after the end of the loop, so the last three function call of the code accesses the "I" that has been updated in the same "global Vo".

Combining the scope chain to see the closure package

In JavaScript, closures are closely related to the scope chain. I believe you must be very familiar with the following closure example, the code is implemented by the closure of a simple counter.

12345678910111213 function counter() {    var x = 0;        return{        increase: function increase() { return++x; },        decrease: function decrease() { return--x; }    };}var ctor = counter();console.log(ctor.increase());console.log(ctor.decrease());

Let's take a look at the execution context and scope chain to see what's going on in the execution of the closure code above.

1. When the code enters global context, a global VO is created

    • Green Arrow pointing to Vo/ao
    • Blue arrow pointing to Scope chain (Vo/ao + all Parent Vo/aos)

2. When the code executes to "var Cter = counter ();" Statement, enter counter execution context; As described in the previous article, this creates counter AO and sets the scope execution for counter chain context

3. When the counter function executes at the end and exits, the ctor in Global Vo is set; it is important to note that although counter execution context exits the execution context stack, However, because members of ctor still refer to counter AO (since Counter AO is the parent scope of the increase and decrease functions), counter AO is still in scope.

4. When the "Ctor.increase ()" Code is executed, the code enters the Ctor.increase execution context and creates Vo/ao,scope chain and sets this for the execution context; Ctor.increase AO will point to counter AO.

    • Green Arrow pointing to Vo/ao
    • Blue arrow pointing to Scope chain (Vo/ao + all Parent Vo/aos)
    • Red arrow pointing to this
    • Black arrow pointing to Parent Vo/ao

I believe that seeing these, will certainly have a clearer understanding of javascript closures, but also understand why counter execution context exited the execution context stack, but counter AO is not destroyed, you can continue to access.

Two-dimensional scope chain lookup

It is understood that the main function of scope chain (scope chain) is to perform variable lookups. However, there is also the concept of the prototype chain (prototype chain) in JavaScript.

Because of the interaction between the scope chain and the prototype chain, a two-dimensional lookup is formed.

For this two-dimensional lookup can be summed up as: When the code needs to find an attribute (property) or descriptor (identifier), the first through the scope of the chain (scope chain) to find the relevant object, once the object is found, The property is found based on the object's prototype chain (prototype chain).

Here's an example to look at this two-dimensional lookup:

1234567891011121314 var foo = {} function Baz () {       object.prototype.a =  ;  &NBSP;&NBSP;&NBSP;&NBSP; return  < Code class= "Java Plain" >function inner () {           console.log (FOO.A); &NBSP;&NBSP;&NBSP;&NBSP; }  }  baz () () ; //Set Bar.a from prototype

For this example, it can be explained that the code first finds "Foo" through the scope chain (scope chain) and eventually finds it in global context, and then because the attribute "a" is not found in "foo", it continues along the prototype chain (prototype Chain) to find the attribute "a".

    • Blue arrows indicate scope chain lookup
    • Orange arrows indicate prototype chain lookup
Summarize

This article introduces the scope and scope chain of JavaScript, analyzes the execution of closures through the scope chain, and further realizes the closure of JavaScript.

At the same time, a prototype chain is combined to demonstrate the search for descriptors and attributes in JavaScript.

Next we'll look at the This property in execution context.

On the scope chain of JS (Ii.)

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.