The new operator creates an instance of a user-defined object type or of a built-in object with a constructor.

function Foo(name){ this.name = name; } let foo = new foo (' xiaoming ');Copy the code

When the code executes new Foo, the following things happen: 1. A new object inherited from foo. prototype is created 2. Call the constructor Foo with the specified arguments and bind this to the newly created object 3. The object returned by the constructor is the result of the new expression. If the constructor does not explicitly return an object, the object created in Step 1 is used. (Normally, constructors do not return values, but users can choose to actively return objects to override normal object creation steps.)

Now that we know how new works, let’s implement one ourselves:

// The first argument is the constructor, and the subsequent arguments are used by the constructor. Function myNew(fn... Args){// Create an empty object const obj = {}; // Link the __proto__ attribute of this object to the constructor prototype object obj.__proto__ = fn.prototype; Const res = fn.apply(obj,args); // Call the constructor as this context and receive the return value const res = fn.apply(obj,args); // If the return value exists and is a reference data type, the constructor returns the value, otherwise the created object is returned. Return Typeof res === 'object'? res:obj }Copy the code

If there is any mistake or not precise place, please give correction, thank you very much!