js handwritten new method

1. What does the new operator do?

        In the process of our programming, the new operator may be often used, so if you want to write the new method by hand, you must know its function, and its function can be divided into the following points:

        1. Create a new empty object

        2. Point the hermit prototype (__proto__) of this new empty object to the prototype object (prototype) of the constructor

        3. Point this in the constructor to the newly created empty object and execute the constructor to return the execution result

        4. Determine whether the returned execution result is a reference type, if it is a reference type, return the execution result, the new operation fails, otherwise return the created new object

2. Implement the new method

        Now that you know the function of the new operator, you can implement its function according to these points, and directly add the code:

function myNew(Fn,...args){
    // 1、创建一个空的对象
    let obj = {}; // let obj = Object.create({});
    // 2、将空对象的原型prototype指向构造函数的原型
    Object.setPrototypeOf(obj,Fn.prototype); // obj.__proto__ = Fn.prototype 
    // 以上 1、2步还可以通过 const obj = Object.create(Fn.prototype) 实现
    // 3、改变构造函数的上下文(this),并将参数传入
    let result = Fn.apply(obj,args);
    // 4、如果构造函数执行后,返回的结果是对象类型,则直接将该结果返回,否则返回 obj 对象
    return result instanceof Object ? result : obj;
    // return typeof result === 'object' && result != null ? result : obj

}

Guess you like

Origin blog.csdn.net/m0_72838183/article/details/127174649