Lexical analysis and variable promotion

1.1 Creating variables

Var ES = let/const;

Variables defined by var have no concept of blocks and can be accessed across blocks rather than functions. Variables defined by lets can only be accessed in the block scope, not across blocks or functions. Const is used to define constants, must be initialized (that is, must be assigned), can only be accessed in the block scope, and cannot be modified. (For const declared reference types, const only guarantees that the pointer does not change. Modifying an object’s property does not change the object’s pointer, so it is allowed.)

Second, var can be used first and declared later. Let must be spoken before use. Third, var allows multiple declarations of the same variable in the same scope. Let and const do not allow this. Fourth, in the global context, global variables based on let declarations have nothing to do with the global object GO (window); Var declares variables that map to GO. Fifth: Solving temporary dead zones:

Log (typeof a) //undefined will not be returned when checking for an undeclared variable type. Console. log(typeof a)// Let a cannot be used without a declaration

Let /const/function uses the curly braces (except for functions) as a new block-level context. Using this mechanism, you don’t need to build closures to store looped event bindings and the like

1.2 Variable Promotion

When the browser opens up the stack for code execution, the code does not execute immediately from the top down. Instead, it continues to do something: declare and define all var and function keywords in the current scope in advance => variable promotion mechanism.

  • Var is only declared in advance, no assignment, default is undefined.
  • Declaration with function plus assignment.
  • Without the vara=3Represents global Settingswindow.a=3And in the global scopevar a=3It’s the same;
// There is no error in this code because of the variable promotion mechanism.
      console.log(foo);//undefined
      bar();/ / 2
      var foo = 1;
      function bar() {
        if(! foo) {var foo = 2;
        }
        console.log(foo);
      }
Copy the code

In the variable promotion phase, when braces, judgment bodies, etc., are encountered, variable promotion is performed regardless of whether the condition is true or not, whereas in older browsers, functions are declared and not assigned.

      console.log(foo);//foo() {}
      function foo() {}
Copy the code
      console.log(foo);//undefined
      {
        function foo() {}}Copy the code

In ES6 syntax, there is block-level scope, where let /const/function takes the current curly brace (in addition to the function) as a new block-level context. For compatible ES3 and ES6, bring the function of a () {} in the global statement, processed under private, also in this line, no longer under private processing, but the browser will all the current code for the operation of a mapping to a global, compatible ES3, code behind but he doesn’t have anything to do with global. The pears are as follows:

      var a = 0;
      if (true) {
        a = 1;
        function a() {}// The previous operations on a map a copy to the global, the latter to keep their own
        a = 11;
        console.log(a);/ / 11
      }
      console.log(a);/ / 1
Copy the code
      var a = 0;
      if (true) {
        a = 1;
        function a() {}
        a = 11;
        function a() {}// The previous operations on a map a copy to the global, the latter to keep their own
        console.log(a); / / 11
      }
      console.log(a); / / 11
Copy the code
      {
        function foo() {
          alert("1");
        }
        foo = 1;
        function foo() {
          alert("2");
        } // map the previous operation on a to the global copy (including his own deletion)
        foo = 2;
        console.log(foo); / / = > 2
      }
      console.log(foo); / / = > 1
Copy the code

Stack memory and garbage collection mechanism

Stack memory: The environment stack (ECStack), also known as stack memory, in which the browser allocates a chunk of computer memory for code to execute.

Basic data types are stored on the stack. The reference data type pointer is stored in stack memory

Heap memory: Browsers put built-in properties and methods into a separate memory,

A reference data type creates a heap of memory, stores things in it, and finally places addresses on the stack for code to associate with;

There are a variety of scope in JS (global, function private, block level private), before the code execution will form its own execution context, and then the context is pushed, after the stack, in the current context and then execute the code; Global executor context (EC(G)) into the stack (ECStack) execution, execution of the code will be the context released (out of the stack), when the page is closed global context out of the stack;

VO variable objects: Each execution context has its own VO variable object, which is used to store variables and functions created in the current context. The function private context is called an AO active object, but is also a variable object. GO global object: it is a heap of memory (stored in the browser’s built-in API property methods), on the browser side, let window point to it VO (G) global variable object: The space used to store global variables in the global context, it’s not GO=, it’s just that in some cases things in VO (G) are related to things in GO;

Function execution:

  • When the function is executed, a new private context EC(FN) is formed, which is executed by string code

  • Push execution, go in from the top, push the whole world down

  • The private context has the private variable object AO(FN), where objects created in the private context are placed;

  • Before executing the code, you also need:

    • ScopeChain:
      (fn),ec(g)>
    • 2. Initialize this to: window
    • 3. Initialize the argument collection: arguments
    • 4. Parameter assignment
    • 5. Variable promotion
    • 6. Code execution

Garbage collection mechanism

1. If there is a large amount of memory (heap/stack/context) that is not released in a project, page performance will be slow. When certain code operations are not properly released, a front-end memory leak can occur [elevation 3]. We use closures as little as possible because they consume memory.

2. Browser garbage collection mechanism/memory collection mechanism

Google: “find references”, the browser periodically looks for references to current memory, if not occupied, the browser will reclaim it; If it is occupied, it cannot be recycled. IE: “reference counting method”, the current memory is occupied once, count the accumulation of 1, remove occupied on the reduction of 1, when reduced to 0, the browser will recycle it.

3. Optimization means: memory optimization; Manual release: Cancel the memory usage.

(1) stack memory: fn = null (null: null pointer object) (2) stack memory: cancel the use of the external heap in the context.

Scope and scope chain

  • When a function is created, the scope of the current function is declared ==> the context in which the current function is created. This is true if the function is created globally[[scope]]:EC(G)



  • When a function executes, a new private context is formedEC(FN), common string code execution (push execution)



  • Initialize the scopeChain (scopeChain) :

    from its own context (the private context formed by the function execution) to the context in which the current function was created (the scope of the current function). In the future, when we encounter a variable in the private context code execution, we first check if it is our own private variable, if it is not, we will find the superior context according to the scope chain. Until we find the big picture.
    (fn),ec(g)>

Closure and its two main functions: protection and preservation

The private context EC(FN) formed during the execution of the function. Under normal circumstances, the code will be released after the execution of the stack. However, in the special case, if something in the current private context is occupied by something outside the context, the context will not be released from the stack, resulting in an undestroyed context. Function execution During the execution of a function, a new private context is created, which may or may not be released.

(1) Protection: divide an independent code execution area, have their own private variable storage space in this area, protect their own private variables from external interference (operate their own private variables and the outside world has no relationship);

(2) Save: if the current context is not freed (as long as something in the context is occupied by the outside), then the stored private variables are not freed and can be used by the lower context, equivalent to saving some values;

The mechanism for protecting and storing private variables is called closures.

5. Advanced programming: multitype function, kerochemical function, compose combination function

6.BAT classic interview questions

  • Topic 1:
      {
        function foo() {}
        foo = 1;

        console.log(foo);/ / 1
      }

      console.log(foo);//function

/* EC(G):{let/const/function... Are considered block-level scopes; Function is only declared in advance, not assigned in advance; 1. Variable promotion: foo 2. Code execution: EC(block) block level scope {AO: foo-----AF0 change foo=1 1 variable promotion: foo 2 code execution: Function foo() {} == "AF0" //foo is declared globally, for es3 compatibility, browsers will map the previous operations on foo to global: execute the global foo-- AF0 foo = 1} code 2: console.log(foo); //function foo(){} } */
Copy the code
  • Topic 2:
      let x = 1;
      function A(y) {
        let x = 2;
        function B(z) {
          console.log(x + y + z);
        }
        return B;
      }
      let c = A(2);
      c(3); / / = = > 7
Copy the code
  • Question 3:
      let x = 5;
      function fn(x) {
        return function (y) {
          console.log(y + ++x);
        };
      }
      let f = fn(6);
      f(7); / / 14
      fn(8) (9); / / 18
      f(10); //  18
      console.log(x); / / 5
Copy the code

  • Question 4:
      let a = 0,
        b = 0;
      function A(a) {
        A = function (b) {
          console.log(a + b++);
        };
        console.log(a++);
      }
      A(1); / / 1
      A(2); / / 4
Copy the code

  • Question 5:
var a = 10,
  b = 11,
  c = 12; //c=3
function test(a) {
  a = 1;
  var b = 2;
  c = 3;
}
test(10);
console.log(a, b, c);
Scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope: scope } 2: console.log(a, b, c); 2: console.log(a, b, c); // 10,11,3 */
Copy the code
  • Question 6:
var a = 4;
function b(x, y, a) {
  console.log(a);
  arguments[2] = 10;
  console.log(a);
}
a = b(1.2.3);
console.log(a);
// 3 10 undefined
/* EC (G) : {a=4, function b(){... } scope:EC(G) parameters: x,y,a A =b(1,2,3) -->a=AF0(1,2,3) form EC(a) console.log(a)==>undefined} EC(a) private context implementation {parameter assignment: x=1,y=2,a=3,a=10 variable promotion code execution:  console.log(a); ==>3 arguments[2] = 10; a=10 console.log(a); ==>10 Return a=undefined} */ after the function is executed
Copy the code
  • Problem 7: Initialize the collection of arguments
function func(x, y, z) {
  x = 100;
  console.log(arguments[0]);
  y = 200;
  console.log(arguments[1]);
  z = 300;
  console.log(arguments[2]);
}
func(1.2); //100 200 undefined
Arguments :{0:10,1:20,length:2} Parameter assignment :x=10,y=20,z=undefined Mapping :x-- argunments[0] y-- argunments[1] z---argunments[2] */
Copy the code
  • Question 8:
var a = 9;
function fn() {
  a = 0;
  return function (b) {
    return b + a++;
  };
}
var f = fn();
console.log(f(5));
console.log(fn()(5));
console.log(f(5));
console.log(a);
/* EC(G) Global context :{VO: a=9 fn=AF0 f=AF0() a=0 f=BF0 A =1, a=0, a=1, a+1=2 Variable promotion: a code execution: f=fn() form EC(fn) context :{AO: variable promotion: code execution: Return function (b) {return b ++; }; Assign this function as a result to f=BF0}} AF0 function heap: {' a = 0; return function (b) { return b + a++; }; Function (b) {return b + a++; }; } global code execution 1: console.log(f(5)); { console.log(f(5)); This is equivalent to printing console.log(5+a++); //5+0=5 private: b=5 global: a=0 a++=0 then execute 2: console.log(fn()(5)); Function (b) {return b ++; }; 3: console.log(f(5))// 5+1=6 console.log(a); 4: console.log(a); / / 2 * /
Copy the code
  • Question 9:
var test = (function (i) {
  return function () {
    alert(i * 2); }; }) (2);
test(5); / / 4
Copy the code
  • Question 10:
var x = 5,
  y = 6;
function func() {
  x += y;
  func = function (y) {
    console.log(y + --x);
  };
  console.log(x, y);
}
func(4);
func(3);
console.log(x, y);
/* EC(G) global context :{VO: x=5,y=6,func=BF0, x=11, x=10 Variable promotion: x,y,func, code execution: func(4)-- AF0(4) Form EC(Fn) context :{AO: variable promotion: code execution 1: X +=y == "x=11 assigned to global code execution 2: func=BF0 parameter: y code execution 3: console.log(x, y); } code execution func(3)-- BF0(3) form EC(Fn1) context: {AO: y=3 Variable promotion: code execution 1: y+--x =3+10=13 global x=10 // output 13} code execution: console.log(x, y); {x += y; func = function (y) { console.log(y + --x); }; console.log(x, y); } BF0 function heap: {console.log(y + --x); } * /
Copy the code
  • Question 11:
function fun(n, o) {
  console.log(o);
  return {
    fun: function (m) {
      returnfun(m, n); }}; }var c = fun(0).fun(1);
c.fun(2);
c.fun(3);
/* EC(G) global context :{VO: fun=AF0,c=fun(0).fun(1)[now to execute function],c=BF0 variable promotion: fun,c, code execution: C =fun(0).fun(1)-- "AF(0).af0 (1) form EC(Fn1) context: {AO: n=1,o=0 variable promotion: code execution 1: console.log(o); Return {fun: function (m) {return fun(m, n); }, return an object to form an object heap store BF0 code execution 3: BF0. Fun (1) executes BF1(1) inside the function to form BF1(1) context: {AO: m=1 variable lift: code execution: Return fun(m, n) //m=1, n=0, == "return fun(1,0)===>0 and return BF0 to c}}; } code execution: c.sun (2); If ==>m=2,n=1==>fun(2,1); = = > m = 3, n = 1 = = > fun (3, 1) / / 1} AF0 function heap parameters as: n, o {the console. The log (o); return { fun: function (m) {return fun(m, n); }}; Function (m) {return fun(m, n)} */
Copy the code
  • Question 12:
      let a = 1;
      function fn1() {
        let a1 = 2;
        function fn2() {
          let a2 = 3;
          function fn3() {
            let a3 = 4;
            a = a1 + a2 + a3;
            console.log(a);
          }
          fn3();
        }
        fn2();
      }
      fn1();/ / 9
Copy the code

A typical case of closures:

Closures are a special case of scope application: the look-up of a closure’s free variable is from where the function is defined to the parent scope

  • Problem 13:1. Functions are passed as arguments
 let a = 100;
      function f1() {
        console.log(a);
      }
      function f2(f) {
        let a = 200;
        f();
      }
      f2(f1);/ / 100
Copy the code
  • Problem 14:2. The function is returned as a return value

function create(){
    // The function created in this file will use the data in this file first
let a=100
return function(){
    console.log(a)
}
}
let fn=create()
let a=200
fn();/ / 100
Copy the code
  • Question 15:3. Closure applications: Hide data and provide only apis
 function createCache() {
        const data = {}; // It is hidden
        return {
          set: function (key, value) {
            data[key] = value;
          },
          get: function (key) {
            returndata[key]; }}; }const c = createCache();
      c.set("a".100);
      console.log(c.get("a"));
Copy the code
  • Question 16:
let a;
      for (let i = 0; i < 10; i++) {
        a = document.createElement("a");
        a.innerHTML = i + "<br>";
        a.addEventListener("click".function (e) {
          e.preventDefault();
          alert(i);
        });
        document.body.appendChild(a);
      }
Copy the code