preface

To implement the new operator manually, you must know what the new operator does.

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

When you call the new operator, you do something like this:

  1. Create an empty object.
  2. Link the prototype of the newly created object to the prototype of the object to be instantiated (that is, modify the prototype of the new object).
  3. Execute the code in the constructor by setting this context object as the newly created object.
  4. If the function does not return an Object (of type other than Object), it returns this (new Object).

Code implementation

function myNew(constructor, ... args) {

  if (typeof constructor! = = 'function') throw TypeError('Parament \'constructor\' is not a function.') / /Object.create(The) method creates a new object, using an existing object to provide the value of the newly created object__proto__. // Step 1const obj = Object.create(constructor.prototype// Execute the constructor code and assign the constructor's scope to the new object before executing // Step 3const result = constructor.apply(obj, args// If the constructor returns one of the six basic data types (Null, Undefined, Number.Boolean.Symbol.StringInstead of returning these values, an object is returned. If it isObjectType (Functoin.Array.Date.RegExg.Error), the object is returned directly. //typeof nullWill be equal to 'object', so manually excludenull/ / step 4if ( (typeof result === 'object' || typeof result === 'function') && result ! = =null ) return result
  return obj
}
Copy the code

use

function Person(name, gender) {
  this.name = name
  this.gender = gender
}

Person.prototype.sayHello = function () {
  console.log('Hello, my name is a ' + this.name + '. ')}const maxin = myNew(Person, 'maxin'.'male')
console.log(maxin)
maxin.sayHello() // Hello, my name is a maxin.
Copy the code

Console print result:

As you can see, we have implemented the new operator.