preface

First of all, objects have a prototype and a prototype chain. Through the prototype chain, we can find the “inheritance” of objects. We can find the parameters and methods of the parent class and the top-level Object through the prototype chain, and use them. An object contains an implicit prototype and an explicit prototype. Constructors find their prototypes in Prototype, and instance functions find their prototypes in proto.

Create an object

There are generally three methods for creating objects: literals, constructors, and Object.create

Var o1 = {name: ‘o1’} var o2 = new Object({name: ‘o2’})

Var M = function(name) {this.name = name} var o3 = new M(‘o3’)

Create var P = {name: ‘P’} var o4 = object.create (P)

The difference between a constructor and a normal function

If a function is instantiated by a new instance, then that function is a constructor and constructors are always capitalized and constructors have their own this, whereas normal functions have this pointing to the window

Constructor, instance function, prototype object, prototype chain

Constructor:

Creates a function that is instantiated by new

Example function:

Instantiate a function with new

Prototype object:

A prototype constructor on which you can add properties and methods

The prototype chain:

Examples can be obtained by using proto to get a prototype of the constructor

The relationship between them

The central character here is the constructor, which can use prototype to get its prototype, which can refer back to the constructor using constructor, or create an instance using new, which can get the prototype of the constructor using proto. The constructor’s prototype object can be viewed as an instance of the parent function as shown below:

The principle of instanceof

Instanceof is used to check whether the constructor’s prototype property appears on the prototype chain of an instance Object. Typeof is used to check whether the constructor’s prototype property appears on the prototype chain of an instance Object. Determines whether an instance object is on the object’s prototype chain. Instanceof, however, can’t tell if the result is a constructor of its own, so you can use the instance object for more accurate judgment

New operator

A new object is created that inherits from the foo. Prototype constructor foo: when executed, the corresponding pass is passed in, and the context (this) is specified as the new instance. New foo is the same as new foo(), and can only be used if no arguments are passed. If the constructor returns an “object”, that object will replace the entire result of new. If the constructor returns no object, the result of new is the object created in Step 1