recognize JavaScript scopes

Source: Internet
Author: User

The scope chain of JavaScript

This is a very important point of knowledge, and understanding the scope chain of JavaScript can help us understand a lot of the ' anomalies ' problem.

Let's take a look at a small example of what I said earlier in the statement.

    var name = ‘乐正闯皇‘;    function echo() {        alert(name);        var name = ‘mm‘;        alert(name);        alert(age);    }    echo();

For this example, there is no contact with this aspect of the time, the first reaction is to be entangled, this first name, whether to call the global variable name, or the name of the function inside, if the global call, but the function is also used to define and assign the inside of the function, if you call the local variables inside the functions, So is his value a mm? Or are you referring to the global ' joy is breaking the Emperor '?

So this little example would have the wrong answer:

    乐正闯皇    mm    [脚本出错]

In fact, knowing the advance description in the function, you know that this is not true.

    undefined    mm    [脚本出错]

It should be so, why is this the answer, in advance to declare what this is? Everything that involves the scope chain of JavaScript.

Principle

First of all, the principle of the scope of javascript:

There is a very incisive description in the JavaScript authoritative guide: the functions in JavaScript run in their defined scopes, not in the scopes they are run in.

In addition, there is a very important concept in javascript: in JavaScript, everything is the object, and so is the function.

In JS, the concept of scope is similar to other languages, and each time a function is called, it enters a scope within a function, and when returned from the function, the scope before the call is returned

The syntax style of JS is similar to C + +, but the scope implementation is different from that of C + +, not by "stack", but by using a list, as described in ECMA262:

    • The scope of any execution context moment is implemented by the scope chain (scope chain, described later)
    • When a function is defined, the scope chain that defines the moment is linked to the [[scope]] property of the Function object
    • When a function object is called, an active object (that is, an object) is created, and then, for each function's formal parameter, it is named as the active object's named property, then the active object is the front-end of the scope chain (scope chain) at this time, and this function object's [[ Scope]] added to scope chain.

Let's look at an example:

    var func = function(lps, rps){        var name = ‘乐正闯皇‘;        ........    }    func();

When executing the FUNC definition statement, a [[scope]] property is created for the function object (internal property, only the JS engine can access, but several Firefox engines (SpiderMonkey and Rhino) provide a private property __parent__ to access it ), and link this [[scope]] property to the scope chain on which it is defined (described later), because Func is defined in the global environment, at this point [[scope]] simply points to the global Active object window active.

When the func is called, an active object is created (assumed to be aobj, created by the JS engine precompiled moment, described later), and the Arguments property is created, and then the object is added with two named properties Aobj.lps, Aobj.rps; For each local variable and function definition declared in this function, it is named as the Name property of the active object.

The call parameter is then assigned to the shape parameter, and the value is undefined for the missing invocation argument.

The active object is then taken as the front-end of the scope chain, and the Func's [[Scope]] property points to the top-level activity object that defines the func, adding to the scope chain.

With the above scope chain, in the event of identifier parsing, the property of each active object of the current scope chain list is queried backwards, and returned if the same name is found. Not found, that is, the identifier is not defined.

Notice that because the [scope] property of a function object is determined when a function is defined, not when it is called , as in the following example:

    var name = ‘乐正闯皇‘;    function echo() {        alert(name);    }    function env() {        var name = ‘mm‘;        echo();    }    env();

The result of his operation is: Le is breaking the emperor

Combining the above knowledge, let's take a look at the following example, and remember the classic JavaScript authoritative guide, wherefunctions in JavaScript run in the scope they are defined in, not in the scope they are running. :

    function factory() {        var name = ‘乐正闯皇‘;        var intro = function(){            alert(‘I am ‘ + name);        }        return intro;    }    function app(para){        var name = para;        var func = factory();        func();    }    app(‘mm‘);

When the app is called, scope chain is made up of the {Window Activity Object (Global)}->{app}.

When you first enter the app function body, the app's active object has a arguments property, and the other two values are undefined properties: Name and Func. And a property with a value of ' mm ' para;

The scope chain at this time is as follows:

    [[scope chain]] = [        {            para : ‘mm‘,            name : undefined,            func : undefined,            arguments : []        }, {            window call object        }    ]

When calling into the factory function body, the factory scope chain at this time is:

    [[scope chain]] = [        {            name : undefined,            intor : undefined        }, {            window call object        }    ]

Notice that the active object of the app is not included in the scope chain at this time.

When defining the intro function, the intro function's [[scope]] is:

    [[scope chain]] = [        {            name : ‘乐正闯皇‘,            intor : undefined        }, {            window call object        }    ]

After returning from the factory function, the identifier parsing occurs when Intor is called in the app, and the Sope chain at this point is:

    [[scope chain]] = [        {            intro call object        }, {            name : ‘乐正闯皇‘,            intor : undefined        }, {            window call object        }    ]

Because the scope chain, the factory activity object is not included. Therefore, the result of the name identifier resolution should be the name attribute in the factory active object, which is the ' joy is breaking the Emperor '.

So the result of the operation is: I am happy to break the emperor

At this point, a complete running process, clearly readable, "functions inJavaScript are run in their defined scopes, rather than in the scope in which they are run." "What is this saying?" he said.

To explain some of the above questions, you have to talk about JavaScript precompilation.

Javascriptの Pre-compilation

Pre-compiled, learned C and so on we all know, but the problem comes, JavaScript is a scripting language, JavaScript execution is a process of translation execution, that in JavaScript execution, there is no similar to the process of compiling?

If you are not sure, first pass an example:

    alert(typeof fun); //function    function fun() {        alert(‘I am 乐正闯皇‘);    };

What's that? -----I go, is "I am happy to break the emperor" but then why, why not undefined it.

Well, yes, in JS, there is a pre-compilation process, JS in the execution of each JS code, will first deal with the VAR keyword and function definitions (function definitions and functional expressions).

As mentioned above, before invoking a function, an active object is created, then the local variable definition in the function is searched, and the function definition is defined, the variable name and function names are the same name properties of the active object, and for the local variable definition, the value of the variable is calculated when it is actually executed. This is simply a undefined.

The definition of a function is a place to note:

    alert(typeof fun); //结果:function    alert(typeof fn); //结果:undefined    function fun() { //函数定义式        alert(‘I am 乐正闯皇‘);    };    var fn = function() { //函数表达式    }    alert(typeof fn); //结果:function

This is the difference between a function definition and a function expression, and for a function definition, the function definition is advanced. The function expression is evaluated during execution.

Speaking of which, by the way, a question:

    var name = ‘乐正闯皇‘;    age = 25;

We all know that variables that are not defined with the VAR keyword are equivalent to global variables and are linked to what we have just learned:

When parsing an identifier for age, because it is a write operation, the identifier is not found when the global window activity object is found, and a value of undefined is returned on the basis of the window activity object.

In other words, age is defined in the top-level scope.

Now, perhaps you have noticed what I just said: JS will first process the var keyword and function definition (function definition and functional expression) before executing each JS code.

Yes, let's take a look at the following example:

    < script >        alert(typeof mm); //结果:undefined    < /script >    < script >        function mm() {            alert(‘I am 乐正闯皇‘);        }    < /script >

Related articles read:

The scope of the JavaScript variable

recognize JavaScript scopes

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.