new理解和实现
NOxONE 7/18/2022 js
new会执行当前的构造函数,并且加入一些语法糖操作:
- 将this指向新创建的obj
obj.__proto__
指向构造函数的prototype- 执行构造函数,若这个构造函数没有return一个对象则默认return这个obj
Talk is cheap, show me the code
function new(constructor, ...args) {
// let o = new Object()
// o.__proto__ = constructor.prototype
let o = Object.create(constructor.prototype) // 一行取代两行
let res = constructor.apply(o, args)
return typeof res == 'object' ? res : o
}