Learn JavaScript with me execution context _javascript tips

Source: Internet
Author: User

In this article, I'll delve into the most basic part of JavaScript-the execution context (execution). After reading this article, you should be aware of what the interpreter does, why the functions and variables can be used before the declaration, and how their values are determined.

1. ec-execution environment or execution context

Each time the controller arrives at the ECMAScript executable code, the controller enters an execution context (a very tall concept).

In JavaScript, the EC is divided into three categories:

    • Global-Level code-this is the default code-running environment, and once the code is loaded, the engine first enters the environment.
    • Function-Level code-when a function is executed, the code in the body of the function is run.
    • Eval code-code that runs within the Eval function.

EC establishment is divided into two phases: into the execution context (creation phase) and execution phase (activation/execution code).

1, enter the context stage: occurs when a function call, but before executing the specific code (for example, before the function parameters are materialized)
Create scope chain (scope Chain)
Create variables, functions, and parameters.
Ask for the value of "this".
2), Execution code phase:
Variable Assignment
Function reference
Interpret/execute other code.
We can consider the EC as an object.

ec={
  vo:{/* functions arguments objects, parameters, internal variables, and function declarations */},
  this:{},
  scope:{/* Vo and all the parent execution context VO/}
}

Now let's look at a code example that contains global and function contexts:

As a simple example, we have a global context circled by a purple border and three different function contexts that are green, blue, and orange, respectively. Only the global context (a variable) can be accessed by any other context.

You can have as many function contexts as you want, and each time you invoke a function to create a new context, a private scope is created, and any variables declared within the function cannot be accessed directly outside of the current function scope. In the above example, the function can access the variable declaration outside the current context, but cannot access the internal variable/function declaration in the external context. Why is this happening? How exactly is the code interpreted?

2, ecs-execution context stack

The execution context of a series of activities logically forms a stack. The bottom of the stack is always the global context, and the top of the stack is the current (active) execution context. When switching between different execution contexts (exiting and entering the new execution context), the stack is modified (either through a stack or a fallback).

Press stack: global ec-> local ec1-> local ec2-> current EC
out Stack: global ec<-local ec1<-local ec2<-current EC

We can represent the environment stack in the form of an array:

ecs=[local EC, global EC];

Each time the controller enters a function (even if the function is recursively called or as a constructor), the operation of the stack occurs. Procedures are similar to push and pop operations for JavaScript arrays.

The JavaScript interpreter in the browser is implemented as a single thread. This means that only one thing can happen at the same time, and other lines or events will be placed in queues called execution stacks. The following figure is an abstract view of a single stacks:

We already know that when the browser first loads your script, it will default into the global execution context. If you call a function in your global code, the sequence of your program goes into the called function, wears a new execution context, and pushes the newly created context to the top of the execution stack.

If you call other functions within the current function, the same thing will happen here. The execution flow of the code enters the internal function, creates a new execution context, and presses it onto the top of the execution stack. The browser will always perform the execution context at the top of the stack, and once the current context function finishes, it will be ejected from the top of the stack, and the context control will be given to the current stack. The following example shows the execution stack call procedure for recursive functions:

(function foo (i) {
  if (i = = 3) {return
    ;
  }
  else {
    foo (++i);
  }
} (0));

This code calls itself three times, each time give me a value plus one. Each time the Foo function is invoked, a new execution context is created. Once the context is finished, it pops up from the top of the stack and returns control to the context below until the global context is left.

There are 5 key points to remember about the execution stack (call stack):

    • Single Thread.
    • Synchronous execution.
    • A global context.
    • Unrestricted function context.
    • Each time a function is invoked to create a new execution context, including calling itself.

3, vo-Variable object

Each EC corresponds to a Variable object VO, in which all variables and functions defined in the EC are stored in their corresponding VO.

Vo is divided into global context Vo (Global object, Globe object, we usually say global objects) and the function context of AO.

VO: {
 //The data in the context (function arguments), function declaration (FD), variable declaration (VAR))
}

1 when entering the execution context, VO's initialization process is as follows:

The formal parameter of a function (when entering the execution context of a function)--a property of a variable object whose property name is the name of the formal parameter, whose value is the value of the argument, and the value of undefined for parameters that are not passed;

function declaration (functiondeclaration, FD)--a property of a variable object whose property name and value are created by a function object, and replaces its value if the variable object already contains an attribute of the same name;

Variable declaration (var,variabledeclaration)--a property of a variable object whose property name is the variable name and the value is undefined; If the variable name is the same as the name of the function that has already been declared or the parameter name of the function, it does not affect the existing property.
Note: The process is sequential.

2. When executing the code phase, some attribute undefined values in VO will be determined.

4. AO active Object

In the execution context of a function, VO is not directly accessible. It mainly acts as a role called active object (Activation Object) (short: AO).
How do you understand that when the EC environment is a function, we visit AO instead of VO.

VO (functioncontext) = = AO;

AO is created when it enters the execution context of a function and initializes a arguments property for the object, which is the arguments object.

AO = {
 arguments: {
  callee:,
  length:,
  properties-indexes://function parameter value
 }
};

The form of FD can only be as follows:

function f () {

}

When the function is called Executioncontextobj is created, but before the actual function executes. This is the first stage that we mentioned above, the creation phase. At this stage, the interpreter scans the arguments or arguments that are passed to the function, the local function declaration and the local variable declaration, and creates the Executioncontextobj object. The results of the scan will complete the creation of the variable object.

The internal execution order is as follows:

1. Find the code that calls the function.

2, before executing the function code, create the execution context first.
3, into the creation phase:

    • Initialize scope chain:
    • To create a variable object:
    • Creates a arguments object, examines the context, initializes the parameter name and value, and creates a copy of the reference.
    • function declaration for scan context: For each function found, create an attribute on the variable object (specifically the name of the function), which has a reference to the function in memory. If the name of the function already exists, the reference pointer will be overridden.
    • The variable declaration of the sweep context: For each variable declared, create an attribute on the variable object-the name of the variable, and initialize the variable's value to undefined, and if the variable's name already exists in the variable object, no action will be taken and the scan continues.
    • Find the value of "This" inside the context.

4. Activation/Code Execution phase:
Runs/interprets the function code on the current context and executes the value of the assigned variable along with the line of code.

Example

1. Concrete examples

function foo (i) {
  var a = ' Hello ';
  var B = function Privateb () {

  };
  Function C () {

  }
}

foo (22);

When you call Foo (22), the status is created as follows:

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

As you can see, the creation State is responsible for handling the names of the defined attributes, not assigning them specific values, and the processing of formal parameters/arguments. Once the creation phase is complete, the execution flow enters the function and activates/code execution phase, looking at what the function does when it is done:

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

2, vo Example:

alert (x); function
var x = ten;
alert (x);
x =;
function X () {};
alert (x); 20

When entering the execution context,

ecobject={
 vo:{
  x:<reference to Functiondeclaration "x" >
 }
};

When executing code:

ecobject={
 vo:{
  x:20//the same name as function x, replace, first 10, then turn into
 }
};

For the above process, we explain in detail.

When you enter the context, VO is filled with the function declaration, the same stage, and the variable declares "x", but, as mentioned earlier, the variable declaration is after the function declaration and the function parameter, and the variable declaration does not conflict with the function declaration and function parameter of the same name that already exists. Therefore, at the stage of entering the context, Vo fills in the following form:

VO = {};

vo[' x '] = < references the function declaration ' x ' >

//Discovery var x = ten;
If the function "X" is not defined
//Then "X" is undefined, however, in our example
///variable declaration does not affect the function value of the same name

vo[' x '] = < value is not affected, still function >

To execute the code phase, VO is modified as follows:

vo[' x '] = ten;
vo[' x '] = 20;

The following example again sees the variable stored in VO in the context phase (therefore, although the code block of else will never be executed, "B" is still in Vo)

if (true) {
  var a = 1;
} else {
  var b = 2;
}

alert (a); 1
alert (b);//undefined, but not "B are not defined"

3, ao example:

function Test (A, b) {
  var c = ten;
  Function d () {}
  var e = function _e () {};
  (function X () {});
}

Test (10); Call

When entering the execution context of test (10), its AO is:

testec={
  ao:{
      arguments:{
      callee:test
      length:1,
      0:10
    },
    a:10,
    C: Undefined,
    d:<reference to Functiondeclaration "D",
    e:undefined
  }
;

Thus, in the establishment phase, VO in addition to arguments, the function of the Declaration, as well as the parameters are given a specific attribute value, the other variable properties by default are undefined. The function expression does not affect VO, so (function X () {}) does not exist in VO.

When the test (10) is executed, its AO is:

testec={
  ao:{
    arguments:{
      callee:test,
      length:1,
      0:10
    },
    a:10,
    c:10,
    D: <reference to Functiondeclaration "D", e:<reference to
    functiondeclaration "E" >
  }
};

It is visible that only at this stage can the variable attribute be assigned a specific value.

5. Lifting (hoisting) decryption

In the previous JavaScript item, the variables and function declarations were elevated to the top of the function scope. However, no one explained the details of why this happened and learned the new knowledge about how the interpreter creates active objects, and it's easy to see why. Look at the following example:

(function () {

  console.log (typeof foo);//function pointer
  console.log (typeof bar);//undefined

  var foo = ' Hello ', C19/>bar = function () {return
      ' world ';
    };

  function foo () {return
    ' hello ';
  }

} ());

We can answer the following questions:

1. Why can we access it before the Foo declaration?
If we follow the creation phase, we know that the variable has been created in the activation/code execution phase. So before the function begins to execute, Foo is already defined in the active object.

2. Foo was declared two times, why is Foo displayed as a function instead of a undefined or a string?
Although Foo was declared two times, we know that the function from the creation stage has been created inside the active object, which occurs before the variable is created, and if the property name already exists on the active object, we only update the reference.
Therefore, the reference to the Foo () function is first created in the active object, and when we explain Var foo, we see that the Foo property name already exists, so the code does nothing and continues to execute.

3, why bar is the value of undefined?
Bar is actually a variable, but the value of the variable is a function, and we know that the variables are created in the creation phase but they are initialized to undefined.

The above is the entire content of this article, there are detailed problem solving, sample code, to help you better understand the JavaScript execution context, I hope you like this article.

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.