JS event loop mechanism

  • Synchronizing task queue
  • Asynchronous task queue
    • Macro tasks include:setTimeout, setInterval, setImmediate, I/O, UI rendering
    • Microtasks include:process.nextTick, promise.then, MutationObserver
  1. Synchronous and asynchronous tasks enter different execution sites, synchronously into the main thread and asynchronously into the Event Table and register functions
  2. The Event Table moves this function to the Event Queue when the specified thing is done (emphasis)
  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. This process is repeated over and over again, known as an Event Loop.

Js object-oriented understanding

  • Object: Everything is an object
  • Class: subdivision of an object
  • Instance: a concrete thing in a class

Why is js single threaded instead of multi-threaded

  • process: is the minimum CPU resource allocation unit. (is the smallest unit that can have resources and operate independently)
  • thread: is the minimum CPU scheduling unit. (A thread is a unit of program running at one time based on a process. A process can have multiple threads.)

Browser is multi-process placed in the browser, every TAB page opened, in fact, is a new process, in this process, there are UI rendering thread, JS engine thread, HTTP request thread and so on. So, the browser is multi-process.

The main use of JavaScript is to interact with the user and manipulate the DOM. This determines that it has to be single threaded, otherwise it will cause complex synchronization issues. For example, if JavaScript has two threads at the same time, one adding content to a DOM node and the other removing the node, which thread should the browser use?

In order to take advantage of the computing power of multi-core CPUS, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are fully controlled by the main thread and do not operate the DOM. So, this new standard doesn’t change the single-threaded nature of JavaScript.

Js garbage handling mechanism

Memory management: “reachability” refers to values that are accessible or available in a certain way, and they are guaranteed to be stored in memory.

  1. There is a basic set of intrinsically reachable values that cannot be removed for obvious reasons,These values are called roots. Such as:
  • Local variables and parameters of local functions
  • Variables and parameters of other functions on the currently nested call chain
  • The global variable
  • There are other ones, internal ones
  1. If a reference or chain of references can access any other value from the root, the value is considered accessible.

A garbage collector, which monitors all objects and deletes those that are inaccessible

  1. What is garbage? Generally speaking, objects that are not referenced are garbage, which means they have to be cleaned up, with the exception that if several object references form a ring, referring to each other, but the root can’t access them, those objects are also garbage, which means they have to be cleaned up.
  2. How to check garbage?
    1. Mark-sweep GC
    2. The garbage collector gets the roots and “marks” (remembers) them.
    3. It then accesses and “tags” all references from them.
    4. It then accesses the tagged objects and marks their references. All accessed objects are remembered so that the same object is not accessed twice in the future.
    5. And so on until there are unaccessed references that can be accessed from the root.
    6. All objects except the tagged ones are deleted.
    ! [tags deleted] (https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/502fe53626d44e998b49b24ae69d5176~tplv-k3u1fbpfcp-zoom-1.image)Copy the code
    1. Mark-compact
    2. Reference Counting
    3. GC replication algorithm
    4. Conservative type GC
    5. Generational recycling
    6. Incremental GC

Js inheritance

If you want to inherit, you must provide a parent class (who to inherit, provide inherited properties).

  1. Prototype chain inheritance:Make the prototype of the new instance equal to the instance of the superclass.
  • The characteristics of
    1. The properties that an instance inherits are the properties of its constructor, the properties of its parent constructor, and the properties of its parent stereotype. (The new instance does not inherit the properties of the parent instance!)
  • disadvantages
    1. The new instance cannot pass arguments to the superclass constructor.
    2. Single inheritance.
    3. All new instances share the properties of the parent instance. (Properties on stereotypes are shared. If one instance modifies a stereotype property, the other instance’s stereotype property will also be modified!)
  1. Borrowing constructors (class-inherited) :Use.call() and.apply() to introduce the superclass constructor to the subclass function (self-executing (copying) the superclass function in the subclass function)

– Features: 1. Inherits only properties of the superclass constructor, not properties of the superclass stereotype. 2. Shortcomings 1, 2 and 3 of prototype chain inheritance are solved. 3. Multiple constructor attributes can be inherited (call multiple). 4. A child instance can pass parameters to its parent instance.

– Disadvantages: 1. Can only inherit properties of the superclass constructor. 2. Constructor reuse is not possible. 3. Each new instance has a copy of the superclass constructor.

  1. Combinatorial inheritance (combining prototype chain inheritance and borrowing constructor inheritance) (common)It combines the advantages of the two modes, parameter passing and reuse
  • The characteristics of:
    1. Can inherit properties on the parent prototype, can pass parameters, reusable.
    2. The constructor properties introduced by each new instance are private.
  • disadvantagesThe superclass constructor is called twice (memory consuming). The subclass constructor replaces the prototype superclass constructor.
  1. Original type inheritance
    • Focus onWrap an object with a function and return the call to that function. The function becomes an instance or object that can add attributes at will. This is how object.create() works.
    • The characteristics of: Similar to copying an object and wrapping it in a function.
    • disadvantages:
      1. All instances inherit the properties on the stereotype.
      2. Reuse is not possible. (New instance properties are added later)
  2. Parasitic inheritance
  • Focus on: Is to put a shell around the original type inheritance.
  • advantages: There is no custom type created, because it is just a shell that returns the object (this), and this function becomes the new object created.
  • disadvantages: The prototype is not used and cannot be reused.
  1. Parasitic combinatorial inheritance (common)
  • parasitic: Returns an object within a function and then calls it
  • combinationThe prototype of the function is equal to another instance. 2, use apply or call to introduce another constructor in the function, which can pass arguments
  • Focus on: Fixed an issue with composite inheritance
/ / parent -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
function Person(name){ // Add parameters to the constructor
  this.name=name
  this.sayName =function(){
    alert(this.name)
  }
}
Person.prototype.age = 18; // Adds prototype properties to the constructor

// The prototype chain inherits ---------------------------
function Per(){
  this.name = 'panpan';  
}
Per.prototype= new Person(); / / the key
var per1 = new Per();
console.log(per1.age); / / 18

// Instanceof determines whether an element is on another element's prototype chain
console.log(per1 instanceof Person); //true
// Inherit --------------------- from the constructor
function Con(){
  Person.call(this.'ava'); / / the key
  this.age = 21
}
var con1 = new Con()
console.log(con1.name) //ava
console.log(con1.age) / / 21
console.log(con1 instanceof Person) //false

// Combine prototype chain inheritance and borrow constructor inheritance
function SubType(name){
  Person.call(this,name); // Borrow the constructor pattern
}
SubType.prototype= new Person();  // Prototype chain inheritance
var sub = new SubType('lian')
console.log(sub.name) //lian inherits constructor attributes
console.log(sub.age) //18 Inherit the parent stereotype properties

// The original type inherits ---------------------------
// Encapsulate a function container that prints objects and hosts inherited prototypes
function content(obj){
  function F(){}
  F.prototype=obj; // Inherit the passed arguments
  return new F() // Return the function object
}
var sup = new Person();   // Get an instance of the parent class
var sup1 = content(sup)
console.log(sup1.age) //18 Inherit function attributes from the parent class

// Parasitic inheritance ----------------------
// Add a shell to the original type inheritance to pass parameters
function subObject(obj){
  var sub = content(obj)
  obj.name= 'pan';
  return sub
}
// After the declaration, it becomes an object that can add attributes
var sup2 = subObject(sup)
console.log(typeof subObject) //function
console.log(typeof sup2) //object
console.log(sup2.name) //pan

// Parasitic composite inheritance ---------------------
/ / the parasitic
function content(obj){
  function F(){}
  F.prototype=obj; // Inherit the passed arguments
  return new F() // Return the function object
}
// Content is another expression of an instance of F
var con = content(Person.prototype)
// The stereotype chain of the con instance (F instance) inherits the stereotype of the superclass function
// This is more like a stereotype chain inheritance, except that the attributes of the stereotype are inherited

/ /
function Sub(){
  Person.call(this) // Inherit the superclass constructor attributes
} // Solve the drawback of combining the constructor property to call twice
/ / the key
Sub.prototype = con; // Inherit the con instance
con.constructor = Sub;  // Be sure to fix the instance
var sub1 = new Sub();
// The Sub instance inherits constructor attributes, superclass instances, and function attributes from con
console.log(sub1.age)
Copy the code

closure

Closures are used primarily to design private methods and variables. The advantage of closure is that it can avoid the pollution of global variables. The disadvantage is that the closure will be resident in memory, which will increase the memory usage. Improper use is easy to cause memory leakage. In JS, functions are closures, and only functions have the concept of scope

Closures have three features:

  1. Function nested function
  2. Functions can refer to external parameters and variables from within
  3. Parameters and variables are not collected by the F garbage collection mechanism

So what exactly does the new operator do?

  1. Create an empty object, and the this variable refers to the object, while inheriting the function’s prototype.
  2. Properties and methods are added to the object referenced by this.
  3. The newly created object is referenced by this, and this is implicitly returned.