Js scope and scope chain and execution context have to tell the story? (? ??? Omega??? ?)?

Source: Internet
Author: User

Recently in the study of JS, found themselves on the scope, scope chain, activity object of these concepts, understand is not very clear, so read the Big God Blog and other articles at the Tian Xiao Plan, benefit, write this essay is his own reading notes ~.

Scope

First clear a concept, JS only function scope (function-based), there is no block-level scope, that is, only the function will have its own scope, none of the others.

Then, the scope is divided into global scope and local scope.

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.

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

When creating this function, the scope of the function and the scope chain (the scope chain of the function will be used at runtime) is determined, but not when it is called, which is important to the tube.

Scope chain

Each JavaScript function is represented as an object, which is an instance of a function. It contains the accessible properties of our programming definition, and a series of internal properties that cannot be accessed by the program and is used only by the JavaScript engine, where an internal property is [[Scope]], defined by the ECMA-262 standard third edition.

The internal [Scope] property contains a collection of objects in the scope in which a function is created. This collection is called the scope chain of the function, and it determines which data can be accessed by the function . Each object in the scope chain in this function is called a mutable object, expressed as a "key-value pair." When a function is created, its scope chain is populated with these objects, which represent the data accessible in the environment in which this function was created:

1 function Add (NUM1, num2) {2 var sum = num1 + num2; 3 return sum;4}

When the Add () function is created, its scope chain is filled with a single Mutable object that represents all global scope defined variables. This global object contains access interfaces such as Windows, browsers, and documents. As shown: (The scope chain of the Add () function, note that only a very small part of the global variable is drawn here)

The scope chain of the Add function will be used at run time, assuming the following code is running:

1 var total = Add (5,10);

When you run this add function, an internal object is created, called the runtime context, and a run-time context defines the environment in which a function is run. Execution And for each individual run, each run-time context is independent, and multiple invocations produce more of this creation. The run-time context is destroyed when the function is executed.

A run-time context has its own scope chain, which is used to resolve identifiers. When the run-time context is created, its scope is initialized, along with the objects contained by the run function's scope chain [[Scope] property. These values are copied into the scope chain of the run-time context, in the order in which they appear in the function. Once the work is done, a new object called an "active object" is created. This activation object acts as a Mutable object for the duration of the function, and includes access to all local variables, named parameters, parameter sets, and this interface. This object is then pushed into the forefront of the scope chain. When the scope chain is destroyed, the active object is also destroyed together. as follows: (the scope chain when running Add ())

In the process of running a function, identifier recognition is performed for each variable encountered. Identifier recognition this process depends on where to get the data or access the data. This procedure searches the scope chain for the run-time context and finds an identifier with the same name. The search work starts from the scope front end of the activation target that runs the function. If found, the variable with the specified identifier is used, and if not found, the search will enter the next object in the scope chain, which continues to run until the identifier is found or no more available objects are available for the search, which is considered an undefined identifier. It is this search process that affects performance. If you want to know how to write high-performance JS, it is recommended to look at this blog, this summary is also excerpted from it--http://www.cnblogs.com/coco1s/p/4017544.html

Execution Context

There are three kinds of code-running environments in javascript:

    • Global Code
      • Default environment for JavaScript code to start running
    • Function Code
      • Code into a JavaScript function
    • Eval Code
      • Executing code using eval ()

In order to represent a different runtime environment, JavaScript has a concept of an execution context (execution Context,ec) . That is, when the JavaScript code executes, it enters a different execution context, which forms an execution context stack (execution context stack,ecs).

The execution context contains three important concepts, which are linked and poorly understood, which makes it difficult for novices to understand clearly once, as shown in:

Each execution context has three important attributes, a variable object (Variable object,vo), a scope chain (scope chain), and this, and of course some additional properties.

When a piece of JavaScript code executes, the JavaScript interpreter creates the execution Context, in fact there are two phases:

    • The creation phase (when the function is called, but before the function internal code is executed)
      • Create Scope chain
      • Create VO/AO (variables, functions and arguments)
      • Set the value of this
    • Activation/Code Execution phase
      • Set the value of a variable, a reference to a function, and then interpret/execute the code

Here are some details about creating a vo/ao that will directly affect the behavior of the code running.

For the "Create Vo/ao" step, the JavaScript interpreter mainly does the following things:

    • Create and initialize the arguments object based on the parameters of the function
    • Scan function Internal code, find function declaration (Functions Declaration)
      • For all function declarations found, save the function name and reference to the Vo/ao
      • If a function with the same name already exists in the Vo/ao, then overwrite
    • Scan function Internal code, find variable declaration (Variable declaration)
      • For all variable declarations found, the variable name is stored in Vo/ao and initialized to "undefined"
      • If the variable name is the same as a formal parameter or function that has already been declared, the variable declaration does not interfere with such a property that already exists

Look at the following example:

function foo (i) {    var a = ' Hello ';    var B = function Privateb () {    };    Function C () {    }}foo (22);

For the above code, in the "Create phase", you can get the following execution Context object:

Fooexecutioncontext = {    Scopechain: {...},    variableobject: {        arguments: {            0:22,            length:1        },        i:22,        c:pointer to function C ()        a:undefined,        b:undefined    }, this    : {...}}

During the activation/code execution phase, the execution Context object is updated to:

Fooexecutioncontext = {    Scopechain: {...},    variableobject: {        arguments: {            0:22,            length:1< c19/>},        i:22,        c:pointer to function C ()        A: ' Hello ',        b:pointer to function Privateb ()    }, This    : {...}}
Summarize

The function determines his scope and scope chain (static) when it is defined, and only when the call creates an execution context that contains the parameters at the time of the call, the function declaration and the variable (VO), and the active object (AO). The AO is pressed into the front of the scope chain of the execution context and contains the properties of this, and the scope chain of the execution context is obtained through the scope chain of the function being called (dynamic).

If the above understanding is wrong, please correct me, salute ~

Reference

Http://www.cnblogs.com/coco1s/p/4017544.html

Http://www.cnblogs.com/wilber2013/p/4909459.html

Http://www.cnblogs.com/wilber2013/p/4909430.html#_nav_3

Js scope and scope chain and execution context have to tell the story? (? ??? Omega??? ?)?

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.