js new的过程实现

function myNew(constructor,...args){
    if(typeof constructor!=='function'){
        return new TypeError('constructor must be a function');
    }
    const newObj=Object.create(constructor.prototype);
    const instance=constructor.apply(newObj,args);
    return instance instanceof Object ? result : obj;
 }
function myNew(Constructor, ...args) {
    // 1. 创建一个空对象
    const obj = {};
    
    // 2. 设置对象的原型为构造函数的原型
    // 注意:__proto__ 不是标准属性,但现代浏览器都支持
    obj.__proto__ = Constructor.prototype;
    
    // 3. 调用构造函数,绑定 this
    const result = Constructor.apply(obj, args);
    
    // 4. 返回结果
    return result instanceof Object ? result : obj;
}

 

posted @ 2025-12-25 15:48  howhy  阅读(14)  评论(0)    收藏  举报