当前位置: 代码迷 >> 综合 >> 如何实现JavaScript中的 new 关键字
  详细解决方案

如何实现JavaScript中的 new 关键字

热度:6   发布时间:2024-02-10 05:37:38.0

观察下方的代码:

// 常见构造函数
function Person(name) {this.name = name
}Person.prototype.getName = function() {return this.name
}// new 的模拟方法
const objectFactory = function() {let obj = new Object() // 从Object.prototype上克隆一个对象let Constructor = [].shift.call(arguments) // 取得外部传入的构造器obj.__proto__ = Constructor.prototype // 指向正确的原型let ret = Constructor.apply(obj, arguments) // 借用外部传入的构造器给obj设置属性return typeof ret === 'oject' ? 'ret' : obj // 确保构造器总会返回一个对象
}

测试:

const a = objectFactory(Person, 'Tom')const b = new Person('Tom')Object.getPrototypeOf(a) === Person.prototype // true

至此我们发现objectFactory与new关键字产生了相同的效果

  相关解决方案