自写new

function myNew(constructor, ...args) {
    // 参数验证
    if (typeof constructor !== 'function') {
        throw new TypeError('myNew: First argument must be a function');
    }
    
    // 1. 创建新对象,继承构造函数的原型
    const instance = Object.create(constructor.prototype);
    
    // 2. 执行构造函数
    const result = constructor.apply(instance, args);
    
    // 3. 处理返回值
    // 如果构造函数返回对象或函数,则返回该值;否则返回新创建的对象
    if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
        return result;
    }
    
    return instance;
}

function User(name,age){
    this.name=name;
    this.age=age
}

const user=myNew(User,'aaa',33)
console.log(user.name,user.age)

 

posted @ 2025-11-26 15:53  howhy  阅读(5)  评论(0)    收藏  举报