第十四章:手写new-灵析社区

懒人学前端

  • 第一参数作为构造函数,其余参数作为构造函数参数
  • 继承构造函数原型创建新对象
  • 执行构造函数
  • 结果为对象,返回结果,反之,返回新对象
function myNew(...args) {
        const Constructor = args[0]
        const o = Object.create(Constructor.prototype)
        const res = Constructor.apply(o, args.slice(1))
        return res instanceof Object ? res : o
}
// 使用
function P(v) {
        this.v = v
}
const p = myNew(P, 1) // P {v: 1}


阅读量:673

点赞量:0

收藏量:0