Execution context for JavaScript

Source: Internet
Author: User

While JavaScript is running, it often encounters some "strange" behavior that does not understand why JavaScript works this way.

At this point, you might need to know something about JavaScript execution.

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

For example, the following JavaScript code:

var a = "global var"; function foo () {    console.log (a);} function Outerfunc () {    var b = "var in outerfunc";    Console.log (b);         function Innerfunc () {        var c = "var in innerfunc";        Console.log (c);        Foo ();    }        Innerfunc ();} Outerfunc ()

The code first enters the global execution context, then goes into the execution context of Outerfunc,innerfunc and Foo, and the execution context stack can be represented as:

When the JavaScript code executes, the first entry is always the default global execution Context, so it's always at the bottom of the ECS.

For each execution context there are three important attributes, the variable object (Variable object,vo), the scope chain (scope chain), and this. These three attributes are very important to the behavior of the code, which is described in one of the following.

Of course, in addition to these three attributes, execution context can have some additional properties, depending on the implementation needs.

Vo and AO

As seen from the above, in execution context, the variable object (Variable object,vo) is saved, and the following is a look at what the variable object is.

Variable objects (Variable object)

Variable objects are data scopes that are related to the execution context. It is a special context-sensitive object that stores the variables and function declarations defined in the context. In other words, the following information is included in the general VO:

    • Variable (var, Variable Declaration);
    • function declaration (Functions Declaration, FD);
    • Formal parameters of a function

When the JavaScript code is running, if you try to find a variable, you will find VO first. For the code in the previous example, the VO in Global execution context can be represented as follows:

Note that if the above example code has the following two statements, the Global VO will remain unchanged.

(function/  function expression, FEBaz = "Property of global Object"

In other words, for VO, there are two special cases:

    • function expression (relative to function declaration) not included in Vo
    • There are no variables declared with VAR (this variable is a "global" way of declaring, just adding a property to global, not in VO)
Active objects (Activation object)

Only variable objects of the global context are allowed to be accessed indirectly through the property names of Vo; In the context of function execution, VO is not directly accessible, and the role of Vo is played by the active object (Activation object, abbreviated AO). The activation object is created at the moment of entry into the function context, and it is initialized by the arguments property of the function.

Arguments Objects is an inner object within the function context of the active object AO, which includes the following properties:

    1. Callee: Reference to the current function
    2. Length: The number of parameters that are actually passed
    3. Properties-indexes: is the parameter value of the function (sorted from left to right by argument list)

The relationship between Vo and AO can be understood as that VO will behave differently in different execution context: Vo can be used directly in global execution context, but in function execution context, The AO will be created.

When the above example starts executing Outerfunc, a outerfunc ao is created:

Through the above introduction, we now understand what Vo and Ao are, and their relationship. Here's a look at how the JavaScript interpreter executes a piece of code and sets Vo and AO.

A closer look at execution Context

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 a variable with the same name already exists in Vo/ao, do nothing and continue scanning

Look at the following example:

function foo (i) {    var a = ' hello ';     var 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,            1        },        a:undefined, function C (),b:undefined            },    this: {...}}

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

Fooexecutioncontext = {    scopechain: {...},    variableobject: {        arguments: {            0:22,            1                         }, ON, Function C ()        ' Hello ',         function  privateb ()    },    this: {...}}
Example analysis

The previous introduction of execution Context,vo/ao and so many theoretical knowledge, of course, is to facilitate us to analyze the code of some of the behavior. Here, we will analyze the results with a few simple examples, combined with the above concepts.

Example 1

First look at the first example:

(function() {    console.log (bar);    Console.log (baz);         var bar =;         function Baz () {        console.log ("Baz");    }    }) ()

Running code in Chrome will output after running:

Code Explanation: The anonymous function first enters "create result", the JavaScript interpreter creates a "function execution Context" and then creates the scope Chain,vo/ao and this. As described earlier, the interpreter scans for functions and variable declarations, as the following AO is created:

So, for bar, we get the "undefined" output, and the behavior is that we access the variable before declaring a variable. This is the "hoisting" in JavaScript.

Example 2

Then the above example, make some changes:

(function() {    console.log (bar);    Console.log (baz);         =;    Console.log (Window.bar);    Console.log (bar);         function Baz () {        console.log ("Baz");    }    }) ()

Running this code will get "bar is not defined (...)" Error. When the code executes to "Console.log (bar);" , you will find "bar" in AO. However, according to the previous explanation, the "bar" in the function is not declared by the Var keyword, and all is not stored in the AO, and there is this error.

Comment out "console.log (bar);" and run the code again to get the following result. "Bar" is created during the activation/code execution phase.

Example 3

Now let's take a final example:

(function() {    console.log (foo);    Console.log (bar);    Console.log (baz);         var function (){};         function Bar () {        console.log ("Bar");    }         var bar =;    Console.log (bar);         function Baz () {        console.log ("Baz");    }    }) ()

The code runs with the following results:

In the code, the most "strange" place should be "bar" output, the first is a function, the second time is "20".

It is also very good to explain, back to the front "create Vo/ao" introduction, in the creation of Vo/ao process, the interpreter will first scan the function declaration, and then "foo: <function>" is saved in the AO, but when the interpreter scan variable declaration, although found "var bar = 20; "But because" foo "already exists in the AO, there is no action.

However, when the code executes to the second sentence "Console.log (bar);" , the "Activation/Code Execution phase" has reset the "bar" in AO.

Summarize

This article describes the execution context (execution context) in JavaScript, as well as concepts such as Vo/ao, and finally illustrates the importance of these concepts to our understanding of how JavaScript code works by using several examples.

The "hoisting" in JavaScript can be clearly understood by scanning function declarations and variable declarations for specific details of Vo/ao in the "Create phase". So, understanding the behavior of the JavaScript interpreter, and related concepts, is helpful in understanding the behavior of JavaScript code.

The scope chain and this in execution context are described later in this article.

Execution context for JavaScript

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.