Deep understanding of the JavaScript scope chain

Source: Internet
Author: User

Before the scope of the chain in my eyes is just the call to an object layer up to find their own required variables or functions, if not the return undefined, in fact, it is generally said, but I need to be constantly in-depth.

Remember two words before you dive into your understanding

All objects in 1.js, functions are objects

2. Functions run within the scope they are defined in, not in the scope being executed.

When a function is defined, it contains the [[Scope]] property (because everything in JS is an object, the function is also an object), this property is a function internal property, only the JS engine access is allowed, [[scope]] points to the scope chain (scope Lain), and this time only contains

All global variables.

When a function is called, a "runtime context" internal object is created that contains its own scope chain, which resolves the identifier and initializes it to the internal object [[scope]] (that is, the global variable) of the calling function, as it appears

Copy to the run-time context, in turn, to compose the "active object" and add it to the first of the scope chain. The active object includes all local variables, formal parameters, named arguments, and this, inside the calling function. When the run-time function is destroyed,

The active object is also destroyed.

Said so much, must have been ignorant, to an example digest.

function Add (num1,num2) {    var sum = num1 + num2;     return sum;}

When you define the Add function, create the [scope] property, point to the scope chain (scope chain), and include only global objects such as:

When you call the Add function, create an execution context (execution context) and create the active object (activation object), updating the scope chain, such as:

Every time the calling function encounters a variable, it goes through the identifier parsing to know where to fetch the data and store the data, find out if there is an identifier with the same name, and if not, find the next object until the global variable, if not found, proves that the identifier is not defined.

So, a small problem, why write JS code to avoid using global variables?

Answer: Because a global variable is used, it is necessary to find the last layer in the scope chain, which affects performance.

Based on the above and the second note at the beginning of the article, give an example

function output () {    var name = "Nana";     var function () {        alert (name);    };     return intro;} function a (para) {    var name = para;     var func = output ();    Func ();} A (' Lili ');

When function A is called, the scope chain is:

[[scope chain]] = {

Pare: ' Lili ',

Name:undefined,

Func:undefined,

Arguments: []

},{

Window Call Object

}

The scope chain is: (note: Does not contain the active object of a) when the function output is called

[[scope chain]] = [{

Name:undefined,

intro:undefined

},{

Window Call Object

}]

When defining the intro function, the scope chain is

[[scope chain]] = [{

Name: ' Nana ',

intro:undefined

},{

Window Call Object

}]

When intro is returned from output, a token resolution occurs when a function is called, at which time the scope chain is:

[[scope chain]] = [{

Intro Call Object

},{

Name: ' Nana ',

Intro: ' Undefined '

},{

Window Call Object

}] According to the second sentence beginning with the article, the function runs within the defined scope, not the scope being executed. As the intro function runs within the defined scope. So the final answer is Nana.

Change the scope chain

1>with

function Initui () {    with(document) {        var bd=Body,            links= getElementsByTagName ("a"),            i=0,            len=links.length;          while (I < len) {            update (links[i+ +]);        }        getElementById ("Btninit"). onclick=function() {            dosomething ();}        ;}    }

With can change the scope, seemingly very convenient, but actually affect performance. When the code reads with, the scope chain is changed to show, so the local variables inside all functions need to be found a second time to be accessible, affecting performance and avoiding use.

2>try-catch

When the try code block exception occurs, the execution of the catch statement, the scope will be like the above temporary changes, then, the local variables can only be found in the second time to match to affect performance, but try-catch in the debugging is very helpful, so do not have to completely avoid. Note: When you finish executing the Catch statement, the scope chain is restored back.


Optimization:

1> try to avoid using global variables
The 2> cache variable, which is cached to a local variable using more than once global variables.

Pre-compilation

Every time I talk about the scope chain, I have to mention precompilation.

At each pre-compilation, look for the Var keyword, and then find the function definition,

Let's see an example!

Console.log (a); var a = ten; Console.log (a); Console.log (typeof  func); Console.log (typeof d); function func () {} var function () {};console.log (typeof D);

Guess what it will output?

The answer is: undefined function undefined function

Did you guess right?

First, variables are found at precompilation, and the VAR keyword is simply assigned to undefined, which is only assigned when executed. var a = 10, equivalent to Var A; A = 10; Therefore, the first output undefined, the second A has been executed, so the output is 10.

Again, the function is found at precompilation, and the function expression is executed only during execution, so the third print function, the fourth print undefined, and the fifth print function.

Resources:
Http://naotu.baidu.com/viewshare.html?shareId=av8cg0e3dckw&qq-pf-to=pcqq.group
Http://www.cnblogs.com/lhb25/archive/2011/09/06/javascript-scope-chain.html

Deep understanding of the JavaScript scope chain

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