1. 先创建一个新对象
    2. 新对象内部的 [[ Prototype ]] 指针被赋值为构造函数的 prototype 属性;
    3. 构造函数内部的 this 指向这个新对象
    4. 执行构造函数内部的代码(给新对象添加属性)
    5. 如果构造函数返回一个对象(非 null),则返回该对象;
      否则,返回刚创建的新对象
    1. function myNew(constructor, ...params) {
    2. // const obj = {}; // const obj = Object.create(null);
    3. // Object.setPrototypeOf(obj, constructor.prototype);
    4. const obj = Object.create(constructor.prototype);
    5. const res = constructor.apply(obj, params);
    6. const type = typeof res;
    7. return ((type === 'object' && res !== null) || type === 'function' ) ? res : obj;
    8. }

    案例测试:

    1. function person(name, age) {
    2. this.name = name;
    3. this.age = age;
    4. // return null;
    5. }
    6. const p = myNew(person, '布兰', 12);
    7. console.log(p); // { name: '布兰', age: 12 }
    8. const q = new person('布兰', 12);
    9. console.log(q); // { name: '布兰', age: 12 }