JavaScript executes procedures in the V8 engine

Non-function execution

var num1 = 20;
var num2 = 30;
var result = num1 + num2;
console.log(result);
Copy the code
  1. Code for parsing, V8 engine internal parsing intoAST syntax treeIt’s going to help us create oneGlobalObject(GO)Object with the following contents:
var GlobalObject = {
    String: "String class".Date:"Date class".Number.setTimeout.num1: undefined.num2: undefined.result: undefined.window: GlobalObject
}
Copy the code

All variables are precompiled and no values are assigned

  1. Run the code
    • To execute code, V8 has an internal execution context stack (function call stack:Execution Context Stack, ECStack)
    • ECStack is generally used to execute functions because there are no functions in the global code that we execute and because we need to create a global scope context in our global code (Global Execution Context,GEC)
    • The global scope contains:Variable Object:GO

Prep work done, start executing code, start givingGlobalObjectNum1 = 20,num2 = 30,result = 50,GOAll variables are stored in the parse phase with an initial value ofundefinedThe code execution begins by performing the associated assignment to get the real result described aboveGOThe parsing process is actually variable promotion.

Function execution procedure

var name = '123';
Foo () => foo
function foo (){
    console.log('foo');
}
Copy the code

Compilation stage:

var GlobalObject = {
    String: "String class".Date:"Date class".Number.setTimeout.name: undefined.foo: undefined.window: GlobalObject
}
Copy the code

If a function is found during compilation, a new memory space is created in the ECStack to hold the function object, which contains two properties:

  • [[sope]]:parent scope
  • The body of the function

This function property holds the address of the function object in the original heap space, and the attribute element points to that address.

foo(123);
function foo(num){
    console.log(m);
    var m = 10;
    var n = 20;
    console.log('foo');
}
foo(321);
Copy the code

The above code execution process:fooinGOSpace stores the memory address, which points to a newly created function storage space, encountered at execution timeECStackCall stack generates a blockFEC.FECIt points to new ground(VO)When the transmission value is 123, in the AO spacenumI have an assignment, and nowundefinedIt’s still in the promotion stage and it turns out to beundefinedAfter the assignment is printed, no reference to the function is found outside the function, so the function is destroyed. If another call occurs, a new section of the ECStack is created to create the FEC object, and the process is repeated until the function space is destroyed.

The scope chain

var name = 'why';
foo(123);
function foo(num){
    console.log(m);
    var m = 10;
    var n = 20;
    console.log(name);
}
Copy the code

The process of finding a variable is actually looking up along the scope chain. Current scope chainscope chainIt contains two pieces of information:VOandParentScopeFor the two nodes, the name variable is found during executionAOThe environment does not define this variable and will go to the upper scopeParentScopeTo find out, andParentSocpeIt is already pointed to when the function is createdGlobalObject, so the upper parent scope will be referencedvar name = "why"

var name = 'why'
foo(123);
function foo(num){
    function bar(){
        console.log(name)
    }
}
foo();
Copy the code

Memory space execution process:

When the function completes, it pops out of the stack and deletes it if there are no references.

Scope chain lookup process:

  • Now ownAOSpace to find
  • ifAOIf the space does not exist, the upper scope GO space will be searched
  • If the upper scopeGOThere is no space will go to the upper space until it is found
  • An error is reported if no assignment is found in outermost space:Uncaguht ReferenceError: xx is not defined

It is recommended to use the name attribute with caution. It may cause the name attribute itself to exist on the Window object

Global scope analysis

var message = "Hello Global";
function foo (){
    console.log(message);
}
function bar (){
    var message = "Hello bar";
    foo();
}
foo();
Copy the code

The confusing point is that the parent scope of a function is determined at compile time, not at execution time. Instead of looking up variables at run time, the find variables phase goes to the parent scope.

Variable environments and records

The EO and AO specifications only apply to the earlier ECMA(5) specifications. In the latest ECMA specification, each execution context is associated with a variable environment to which the variable environment is added as an environment record. For functions, parameters are also added as an environment record.

Scoped interview questions

Topic 1:

var n = 100;
function foo(){
    n = 200;
}
foo();
console.log(n);
Copy the code

Topic 2:

function foo(){
    console.log(n); //undefined
    var n = 200;
    console.log(n); / / 200
}
var n = 100;
foo();
Copy the code

Resolution:

  • I’m going to create one firstGlobalObjectObject, which is stored infooThe address,nThe variables of(undefined)
  • GOObject starts assigning,nThe assignment for100.fooThe function still holds the address
  • functionfooCreate a new spaceAOStart executing code, execute functions from top to bottom
  • printn, found in their own inner spaceAOIt’s been resolved in advancenThe variable, the result is zeroundefiendPrint the second timenThe result is 200 as defined above

Title 3:

var n = 100;
function foo1(){
    console.log(n)
}
function foo2(){
    var n = 200;
    console.log(n);
    foo1();
}
foo2();
console.log(n);
Copy the code

Resolution:

  • First, create a space in heap memoryGlobalObjectUsed to store the above variables,nUndefined,foo1,foo2 are the memory addresses to be created
  • Foo1,foo2 memory space, variable parsing,nisundefined
  • The code enters the execution phase
  • Foo2 internalnThey look inside themselves firstAOIs there spacenVariable assignment, search found:n=200
  • Foo1 internal print n, find if n variable, find no, then go to your own memory upper space, upper spaceGlobalObjectYes, it doesn=100
  • Finally, print n, where n is the global variablen=100

Topic 4:

var a = 100;
function foo(){
  console.log(a);
  return;
  var a = 100;
}
Copy the code

Similarly, the code after return does not execute, but it still assigns undefined to a at compile time. Foo does not search for undefined in the upper scope because it already has the assigned variable a. Supplement:

function other(){
  m = 200; By default, the JS engine takes care of m and adds it to the global variable 'GlobalObject'
}
Copy the code

Topic 5:

function foo(){
    var a = b = 100;
}
foo();
console.log(a);
console.log(b);
Var a = 100; b=100; * /
Copy the code

In the AO space, a is undefined, but in the GO space, A is not defined and B is 100