What does js new do to implement new by hand

What exactly does new do
(1) Create a new object;
(2) Point this in the constructor to the object
(3) Execute the code in the constructor (add attributes to this new object);
(4) Return the new object .

function _new(obj, ...rest){
    // 基于obj的原型创建一个新的对象
    const newObj = Object.create(obj.prototype);

    // 添加属性到新创建的newObj上, 并获取obj函数执行的结果.
    const result = obj.apply(newObj, rest);

    // 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象
    return typeof result === 'object' ? result : newObj;
}

 

function _new( fn ){
    let obj = {}
    obj.__proto__ = fn.prototype
    let result = fn.call(obj)
    return typeof result === 'object' ? result : obj
}

 

Guess you like

Origin blog.csdn.net/lianjiuxiao/article/details/114965888