Re learn JavaScript of front end (3) scope, prototype chain, garbage collection mechanism, closure, event execution sequence


This article mainly introduces the scope, prototype chain, garbage collection mechanism, closure and event execution sequence in JavaScript

Execution environment and scope

1execution environment The definition of
  execution environment : The execution environment defines other data that a variable or function has access to , It determines their respective behaviors. Each execution environment has a variable object associated with it , All variables and functions defined in the environment are stored in this object. Although the code we write cannot access this object , But the parser uses it in the background when it processes the data.
  Global execution environment: in web browser, the global execution environment is considered as window object, so all global variables and functions are created as properties and methods of window object. After all the code in an execution environment is executed, the environment is destroyed, and all the variables and function definitions saved in it are also destroyed. The global execution environment is not destroyed until the application exits, such as closing a web page or browser.
  Function execution environment: each function has its own execution environment. When the execution flow enters a function, the environment of the function will be pushed into an environment stack. After the function is executed, the stack pops up its environment and returns the control to the previous execution environment.
2Scope chain
  1) definition: when code is executed in an environment, a scope chain of variable objects is created. Ensure the orderly access to all variables and functions that the execution environment has access to.
  2) purpose: Ensure the orderly access to all variables and functions that the execution environment has access to. Front end of scope , Is always a variable object in the environment of the currently executing code. If this environment is a function , The active object is treated as a variable object. The active object starts with only one variable , The arguments object ( This object does not exist in the global environment )。 The next variable object in the scope comes from the include ( external ) environment , The next variable object comes from the next containing environment. such , All the way to the global execution environment ; The variable object of the global execution environment is always the last object in the scope chain.
  3) Search process: Identifier parsing is the process of searching for an identifier level by level along the scope chain. The search process always starts at the front end of the scope , And then go back step by step , Until the identifier is found ( If the identifier is not found , It usually leads to errors )。
  4) matters needing attention: the internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment.

Reference from : JavaScript advanced programming ( 3rd Edition ) four . 2 execution environment and scope p73

Prototype inheritance and prototype chain

1The definition of prototype chain
  Prototype chain: each instance object has a private property called__ proto__ )Point to its prototype object. The prototype object also has its own prototype object (__ proto__ )Up to the end of the prototype chain. By definition, null has no prototype and serves as the last link in the prototype chain( Object.prototype .__ proto__ )So the end of the prototype is null, because null does not__ proto__ Property, and returns undefined. Almost all objects in JavaScript are instances of objects at the top of the prototype chain, except Object.create (null)。 When accessing a property or method of an object, if it cannot be found on the current object, it will be found on its prototype. If it still cannot be found, it will be found along its prototype. If it is found, it will return the result. If it is not found, it will be found until the end of the prototype chain is null( Object.prototype .__ proto__ , which points to null), and returns undefined.

2Detailed description of prototype chain
     1) if a creates B through new, then B__ proto__ = A.prototype;
    2 ) Implementation B . a. If a cannot be found in B, it will be found in B .__ proto__ Middle, which is a . If a . If there is still none in the prototype, it will continue to look up. Finally, it will find the object . prototype , If not, because object . prototype .__ proto__ Points to null, so undefined is returned;
     3) at the top of the prototype chain, there must be Object.prototype .__ proto__ ——> null。

3Prototype classification
  Prototype classification:
    A、Function object: its instance is the object of function. Type of obj = = = function “, such as string, number, Boolean, object, function, array, date, regexp and error. haveprotoAnd prototype.
    B、Common objects: Its instance is the object of object. typeof fn === ” object “, asconst obj = {}; const fn = new fun1(){};Only__ proto__。
  proto: implicit prototype.
    1 ) Most of the time__ proto__ It can be understood as ” The prototype of the constructor “。 Prototypes of active pointing construction ( This property points to the prototype of the object ), Through object . create () The created object does not apply to this equation

const obj = {}; obj.__proto__ === Object.prototype;
function fn() {}; fn.__proto__ === Function.prototype

     2) this property is generated automatically when creating a function and object, except null
  prototype: display prototype
     1) this attribute is generated automatically when a function object is created
     2) the attribute is__ proto__ Property points to

function Fun(){}
    //Here's what JavaScript implicitly does; func.prototype .__ proto__  ===  Object.prototype Is true
    Fun.__proto__ = Function.prototype;
    Fun.prototype = {
        constructor: Fun,
        __proto__: Object.prototype

4What does the new keyword do to an ordinary function?:

function myNew(Cons,...args){
        let obj = {};
        obj.__ proto__  =  Cons.prototype ; // execute prototype link
        let res =,args);
        return typeof res === 'object' ? res : obj;

Reference from:
   haven’t you learned JavaScript prototypes and prototype chains yet?
   three diagrams to understand JavaScript prototype object and prototype chain

Garbage collection mechanism

1、 Definition
  garbage collection JavaScript has an automatic garbage collection mechanism, which means that the execution environment is responsible for managing the memory used during code execution. The principle of garbage collection mechanism is to find out those variables that are no longer used, and then release them to occupy memory. For this reason, the garbage collector will periodically perform this operation at a fixed time interval (or a predetermined collection time in code execution).
2Garbage collection method
  1) Mark clear: Right nowmain streamGarbage collection algorithm based on. When a variable enters the environment (for example, a variable is declared in the environment), it is marked as “enter the environment”; when a variable leaves the environment, it is marked as “leave the environment”. When the garbage collector runs, it will mark all variables stored in memory, and then it will remove the marks of variables in the environment and variables referenced by variables in the environment. After that, the marked variables will be regarded as the variables to be deleted, because the variables in the environment can no longer access them. Finally, the garbage collector completes the memory cleaning work, destroys the marked values and reclaims the memory space they occupy.
  2) Reference countJavaScript engines are currentlyNo longer usedThis kind of algorithm. It tracks the number of times each value is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of references to the value is 1. If the same value is assigned to another variable, the number of references to that value is increased by 1. On the contrary, if the variable that contains a reference to this value gets another value, the number of references to this value is reduced by 1. When the number of references to this value becomes 0, it means that there is no way to access this value, so the memory space occupied by it can be reclaimed. In this way, the next time the garbage collector runs, it will free the memory occupied by the values with zero references.
    Defect of reference count: serious problems occur when circular references occur. Circular reference means that object a contains a pointer to object B, and object B also contains a reference to object a. When a circular reference appears in a function, objecta and objectb will continue to exist after the function is executed, because their reference count will never be 0. If this function is called repeatedly, a large amount of memory will not be recycled.
   3Memory optimization
    Optimization method: the best way to optimize memory usage is to save only the necessary data for the code in execution. Once the data is no longer useful, it is best to release its reference by setting its value to null, which is calledDereference. This is used for most properties of global variables and global objects. Local variables are automatically dereferenced when they leave the execution environment. The real effect of dereferencing is to get the value out of the execution environment , So that the garbage collector can recycle it the next time it runs.

Reference: Javascript advanced programming (3rd Edition) 4.3 garbage collection p78


   definition: a closure is a function that has access to a variable in the scope of another function.
2、 The advantages and disadvantages of closure
    a . You can read variables inside a function
     B. the value of variable can always be saved in memory
     C. data hiding and encapsulation
  shortcoming :
     A. overuse of closures can lead to memory leaks
     B. using this object in closures can also cause some problems. In a global function, this is equal to window, and when a function is called as a method of an object, this is equal to that object. However, the execution environment of anonymous function is global, so its this object usually points to window.

3Common ways to create closures
   create another function inside one function and return it.

    function add() {
        let num = 1;
        return function () {
            return ++num;
    const getCount = add();
    getCount(); // 2
    getCount(); // 3

4Why can a closure access a variable in the scope of another function?
Notes : The external function is called FNA , The internal function returned is called FNB
   when FNB is returned from FNA, the scope chain of FNB is initialized to the active object and global object containing FNA function. Therefore, FNB can access all variables defined in FNA. Because the scope chain of FNB always refers to the active objects of FNA, after the execution of FNA, although the scope of the execution environment of FNA is destroyed, its active objects will still be left in memory until FNB is destroyed.

5Clear closure
   setting the variable value of a reference to an anonymous function to null to dereference the function is equivalent to notifying the garbage collection mechanism to clear it. As the scope chain of anonymous functions is destroyed, other scopes (except the global scope) can be safely destroyed.

Reference: Javascript advanced programming (3rd Edition) 7.2 closure p178

The execution order of setTimeout / setinterval and promise in JavaScript

1Execution order of synchronous and asynchronous tasks (regardless of promise)
Re learn JavaScript of front end (3) scope, prototype chain, garbage collection mechanism, closure, event execution sequence
   1. Synchronous and asynchronous tasks enter different execution “places”, enter the main thread synchronously, enter event table asynchronously and register functions
   2. When the specified task is completed, event table will move this function into event queue.
   3. If the task in the main thread is empty after execution, it will go to the event queue to read the corresponding function and enter the main thread for execution
   4. The above process will be repeated, which is often called event loop
   note: asynchronous here refers to setTimeout and setinterval

2Macro task and micro task
Re learn JavaScript of front end (3) scope, prototype chain, garbage collection mechanism, closure, event execution sequence
Tasks in     JavaScript can be broadly divided into two categories: synchronous tasks and asynchronous tasks. In detail, they are divided into macro tasks and micro tasks.
  Macro task (macro task / macro task): tasks initiated by the host (browser, node) are called macro tasks. In other words, the host environment passes a piece of code to the JavaScript engine, and the engine directly executes the code in sequence. This task is also the task initiated by the host. Macro tasks include script, setTimeout and setinterval.
  Micro task (micro task / micro task): Tasks initiated by JavaScript engine are called micro tasks. That’s the promise of ES6 , No browser arrangement required , The JavaScript engine itself can also initiate tasks. Micro tasks include promise and process . nextTick ( node . API in JS )。

3The overall sequence of events
  The overall sequence of events: after entering the whole code (macro task), start the first cycle, first execute all synchronization tasks — > then execute all micro tasks that meet the conditions — > then start from the macro task again, find one of the task queues, finish executing all micro tasks that meet the conditions.

4Case analysis of event cycle, macro task and micro task

    setTimeout(function() {

    new Promise(function(resolve) {
    }).then(function() {


   step analysis:
     1) this code enters the main thread as a macro task
      2) first encounter setTimeout, then register its callback function and distribute it to the macro task event queue
     4) encounter console.log (‘console ‘), execute immediately.
    5 ) The whole code script ends as the first macro task , Then query the micro tasks that meet the conditions , Find the then of promise , implement
      6) the first round of time cycle ends, and then the second round starts. First, start from the macro task event queue, find the callback function corresponding to setTimeout in the macro task event queue, and execute it immediately
    7 ) end
Reference source: this time, thoroughly understand the JavaScript execution mechanism

If there are any mistakes in the above contents, I hope you can point them out. Thank you.

Recommended Today

Analysis of super comprehensive MySQL statement locking (Part 1)

A series of articles: Analysis of super comprehensive MySQL statement locking (Part 1) Analysis of super comprehensive MySQL statement locking (Part 2) Analysis of super comprehensive MySQL statement locking (Part 2) Preparation in advance Build a system to store heroes of the Three KingdomsheroTable: CREATE TABLE hero ( number INT, name VARCHAR(100), country varchar(100), PRIMARY […]