js new 手写实现 new做了哪些事情

new到底做了哪些事情
(1) 创建一个新对象;
(2) 将构造函数中的this指向该对象
(3) 执行构造函数中的代码(为这个新对象添加属性) ;
(4) 返回新对象。

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
}

猜你喜欢

转载自blog.csdn.net/lianjiuxiao/article/details/114965888