New的原理

586 阅读1分钟

new操作符号做了哪些事:

  • 创建一个全新的对象
  • 这个对象的__proto__要指向构造函数的原型prototype
  • 执行构造函数,使用apply/call改变this指向
  • 返回值为object类型则作为new方法的返回值返回,否则返回上述全新对象

实现New的函数

function creatObj(fn, ...args) {
    let instence = Object.create(fn.prototype)
    let result = fn.apply(instence, args)
    if (Object.prototype.toString.call(result) === '[object Object]') {
        return result
    }
    return instence
}

image.png