1. Create a new object

  2. Assigns the scope of the constructor to the new object

  3. Execute the code in the constructor to add attributes to the new object

  4. Returns the newly created object as the return value

 

This process is equivalent to:


var obj  = {};

obj.__proto__ = Object.prototype;

Object.call(obj);

Copy the code

Create an instance Object obj to verify this:


let obj = new Object(a)console.log(obj.__proto__===Object.prototype)     //true

Copy the code

 

Write a function to implement the new function:

New is the keyword, so we’re going to simulate it with a function,new Foo(args) <=> myNew(Foo, args)


function myNew(foo, ... args) {

       /* Create a new object and inherit the constructor's prototype property. This step is to attach obj to the prototype chain equivalent to obj.__proto__ = foo. prototype*/

       let obj = Object.create(foo.prototype)

 

       /* Execute the constructor and bind a new this to it. This step is to enable the constructor to do things like this.name = name. Args is the constructor's input parameter, which is passed */ from myNew because it is emulated with myNew

       let result = foo.apply(obj, args)

 

       If the constructor already returns an object, the object is returned. Normally, the constructor does not return a new instance, but the consumer can choose to return a new instance to override the object created by new or return a new object created by myNew

       return typeof result === 'object'&& result ! = =null ? result : obj

}

 

function Foo(name) {

       this.name = name

}

const newObj = myNew(Foo, 'zhangsan')

console.log(newObj) // Foo {name: "zhangsan"}

console.log(newObj instanceof Foo) // true

Copy the code