The theme

  1. The underlying mechanisms
  2. Closure to understand
  3. This summary

01 Underlying Mechanism

var l = {x: 10}
var g = l
l.y = l = {x: 200}
console.log(l.y)
console.log(g)
Copy the code

1.1 Related Nouns

Nouns encountered when analyzing code execution problems

  1. JS execution platform
    • Different browsers
    • Nodejs
    • webview
    • Does JS execution on any platform require an environment for code execution
  2. Environment execution stack
    • No matter what programming language the code is written in, the final execution takes place in memory
    • Each time the browser loads an interface, it requests a space from the computer’s memory, called the environment execution stack
    • ECS(Execute context stack)
    • It’s like a big container where all future code execution will be done
  3. Execution context
    • A JS file contains many lines of code, and different lines constitute branches, loops, functions, objects and other code blocks
    • If multiple code blocks are executed directly on the environment execution stack, interference and syntax conflicts can easily occur
    • Each code block has its own execution context, which holds the data needed for the current code block to execute
    • The execution context uses EC? (Execution context) said
  4. Into the stack perform
    • The execution environment stack is a first in, last out stack structure
    • Code runs in different execution contexts
    • Different execution contexts are pushed into the stack, and after the code is executed, the decision is made to exit the stack
  5. EC(G)
    • Execution Context Global The global Execution context, created by default when the browser creates an interface
  6. VO(G)
    • Variable Object Global variable object, used to store variables declared in the global context
  7. GO
    • VO is a global object. VO is a global object. VO is not the same thing
    • As an object, it also takes up space, is created when the browser loads the interface, and holds many apis inside it that JS can use directly
    • For example,setTimeout setInterval JSONEtc.
    • To facilitate the use of the API above, a window property is created in VO(G) to point to the current space
  8. The statement
    • Declare a variable with a specific keyword var let const functionvar name
  9. define
    • The definition is to perform an assignment to a variablename = 'tom'

1.2 Base values in the stack

var l = 100
var g = l
g = 101
console.log(l)
/* 01 /* 01 /* 01 /* 01 /* 01 /* 01 /* 01 /* 01 VO(G) exists in the global execution context, which is used to save the data in the current execution context. 04 There will be variable promotion before the code execution, and the variable declared by var is only declared in the promotion stage without defining */
Copy the code

conclusion

  1. The execution environment stack, global execution context, GO are created by default when the browser loads the interface
  2. The EC(G) will have VO(G) internally dedicated to storing data in the current context
  3. The EC(G) context exits the stack after the browser is closed, freeing the corresponding memory
  4. Base type values are stored in stack space
  5. Scope-chain lookups, when the code runs using a variable, are first looked up in the current context, and if not, up until GO

1.3 Reference types in the stack

var g = l
g['y'] = 100
console.log(l.y)
-------------------------------------------------
var l = { x: 10 }
var g = l
g = { y: 100 }
console.log(l.x)
Copy the code

Summary 01 Basic data types (raw values) are stored in stack memory, and reference types are stored in the heap memory space. 02 Each heap memory has a hexadecimal address

1.4 Functions in the stack

Function itself is also an object, for his analysis is generally divided into the creation of function and function execution

var lg = [88.100]
function foo(obj) {
  obj[0] = 100
  obj = [100]
  obj[1] = 200
  console.log(obj)
}
foo(lg)
console.log(lg)
Copy the code

1.4.1 Function Creation

  • The variable promotion phase is both declared and defined for functions
  • The creation of a function is similar to the promotion of a variable. The function name can be thought of as a variable name, except that it contains a declaration + definition
  • A function is also an object, so it is also stored in the heap and then stored on the stack
  • For functions, declaration and definition occur in the promotion phase, so code execution sees code such as function foo(){} and generally does not perform operations
  • When a function is created, its scope is defined, that is, its current execution context
  • When a function is created, it stores the function body in memory as a string

1.4.2 Function execution

  • The purpose of the function execution is to actually run the code stored in memory as a string
  • The code runtime needs to keep the current code segment isolated from the code segment in other contexts, so the function generates a new execution context each time it executes
  • step
    • Determine the scope chain
    • Identify the this in the function body
    • To initialize the arguments
    • Parameter value
    • Variable ascension
    • Function code execution

Parameter assignments at function execution are equivalent to adding attributes to AO(G)

1.5 Closure mechanism

1.5.1 Meaning of Closures

Closures are a mechanism where the code is just a concrete representation, such as a big function nesting a small function and returning a small function

Function generates a new execution context, generally the function of the code execution after need a stack so as to release the memory space occupied by the current context, so as to release its internal statement and value, but if the current data of the execution context (generally are heap memory references) is outside of the current context variables referenced, The context cannot be released, and a closure is formed

The advantage of closures is that they can store some data, such as zCE below. The internal ZCE of a function and the global ZCE do not interfere with each other. Closures can also store data, such as 0x001, which would have been freed after fn, but was referenced by foo in ec (g). So you can let it continue to be used in subsequent code

var zce = 100
function fn() {
  var zce = 200
  return function (a) {
    console.log(a + zce++)
  }
}

var foo = fn()
foo(10)
foo(20)
Copy the code

1.5.2 Closures and garbage Collection

  • The above code operation can be found that the operation of the code needs memory, whether it is stack memory or heap memory, all belong to the computer memory
  • The size of memory space is limited, so it cannot be used indefinitely, so memory management is required, namely garbage collection
  • Chrome, for example, performs garbage collection in time space to complete the collection of memory space
    • Stack memory
      • It is used to store basic data type values
      • When a context finishes execution, if the space inside it is no longer being used by others, it frees that space for garbage collection
    • Heap memory
      • Used to hold reference data types
      • If the heap in context A has code in context A that is still referenced by context B after completion of execution, then the heap memory and the space occupied by context A cannot be released, which is often referred to as closure. If there are too many such code, it will also be A cost to performance
    • Actively null variables when appropriate, freeing references
    • The EC(G) global execution context is created when the browser loads the interface, so it is not reclaimed if the interface is not closed

1.5.3 exercises

let m = 5
function foo(m) {
  return function (n) {
    console.log(n + (++m))
  }
}

let fn = foo(8)
fn(10)
foo(11) (13)
fn(20)
console.log(m)
------------------------------------
let m = 10,
  n = 10
function foo(m) {
  foo = function (n) {
    console.log(m + n++)
  }
  console.log(m++)
}

foo(5)
foo(7) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -function fun(n, o) {
  console.log(o)
  return {
    fun: function (m) {
      return fun(m, n)
    }
  }
}
var c = fun(10).fun(3)
c.fun(6)
c.fun(8)
Copy the code

02 This rule

2.1 This rule

When running JS in a browser platform, the “this” in a non-function usually refers to the window, so this is discussed here during function execution. Note that in ES6+ arrow function, there is no own “this”, the processing mechanism is to use its own “this”

2.1.1 What is This

  1. This is the body of the current function execution (who executed the function), not equal to the current context, current scope
  2. Zce is at the front of pull education
    1. The front end is an action.
    2. Pull education (Execution context)
    3. The zCE body, referred to by this in the current execution context

2.1.2 This scenario is common

  1. event
  2. Common function
  3. The constructor
  4. Arrow function
  5. Force changes to this pointing based on call/bind/apply

2.1.3 rule

  1. event
    1. Whether it’s DOM2 or DOM event binding, this is usually the element being manipulated when the event is triggered
  2. Common function
    1. The function is executed to check if there is a dot in front of it. If there is a dot in front of it, it is the execution body. If there is no dot, it is the window
    2. A special case
      1. This in an anonymous function is window or undefined
      2. This in the callback function is also window or undefined
      3. Bracketed syntax
        1. If there’s only one term in the parentheses, it’s not added
        2. If there are more than one item in the parentheses, the last item is fetched, which is equivalent to copying the function, so the body of the call is window

2.1.4 this practice

(function () {
  console.log(this)
})()

let arr = [1.3.5.7]
obj = {
  name: 'Pull education'
}
arr.map(function (item, index) {
  console.log(this)
}, obj)
------------------------------------------------------
/ /? Ordinary function calls
let obj = {
  fn: function () {
    console.log(this.111)}}let fn = obj.fn;
fn()  // window
obj.fn();  // obj
(10, fn, obj.fn)();
------------------------------------------------------
var a = 3, 
  obj = { a: 5 }
obj.fn = (function () { 
  this.a *= ++a
  return function (b) {
    this.a *= (++a) + b
    console.log(a)
  }
})();
var fn = obj.fn  
obj.fn(6)
fn(4)
console.log(obj.a, a)
Copy the code

–20210729 Live notes