To understand how the new operator works, you need to understand what new does. As we all know, we use the new operator when we instantiate our constructors as objects.

To really master and write a new, you need to know about prototypes and prototype chains and the this binding.

In fact, the internal process of New is very simple, which is basically the following steps:

  1. Create a new object, obj
  2. Points the implicit stereotype of an object to the stereotype object of the constructor
  3. Call the constructor with apply (change this to obj)
  4. Return obj, if the constructor has a value, reference object if the value is a reference type, and obj if it is primitive

Writing:

  function MyNew() {
    // Get the list of parameters, get the constructor and its parameters
    let [ArgFun, ...arg] = [...arguments]
    // Define an empty object
    let obj = {};
    // Prototype pointing
    obj.__proto__ = ArgFun.prototype;
    // Set this to point
    let tartgetObj = ArgFun.apply(obj, arg)
    // Call the constructor with apply (change this to obj)
    return tartgetObj instanceof Object= =true ? tartgetObj : obj
  }
Copy the code

Use:

  function Person(name, age) {
    this.name = name;
    this.age = age;
    console.log('execution')
    return '12'
  }

  let zhangsan = MyNew(Person, 'Joe'.12)
  console.log(zhangsan)

Copy the code