SOURCE

/**
 * 模拟实现 new 运算符
 * new 执行流程:
 * 1. 创建一个空的新对象
 * 2. 将新对象的原型指向构造函数的 prototype
 * 3. 使用新对象作为 this 执行构造函数,传入参数
 * 4. 如果构造函数返回一个引用类型(对象/数组等),则返回该值;否则返回新建对象
 * @param {Function} fn - 构造函数
 * @param  {...any} args - 传给构造函数的参数
 * @returns {object} 实例对象
 */
function myNew(fn, ...args) {
    // 1. 创建空的普通JavaScript对象
    const obj = {}
    // 2. 将新对象的原型指向构造函数的原型对象,实现原型链继承
    Object.setPrototypeOf(obj, fn.prototype)
    // 3. 执行构造函数,绑定this为新建obj,传入参数
    const result = fn.apply(obj, args)
    // 4. 判断构造函数返回值:
    //    如果返回值是对象(引用类型),直接返回该返回值
    //    如果是基本类型 / null,忽略,返回我们创建的 obj
    return result && typeof result === 'object' ? result : obj
}


function Fn(name) {
    this.name = name
}
console.log(myNew(Fn, 'hello'))
console 命令行工具 X clear

                    
>
console