new 操作符做了哪些事情?如何手写一个 new?
new 做了 4 件事
- 创建一个新的空对象
- 将新对象的
__proto__ 指向构造函数的 prototype
- 将构造函数的
this 绑定到新对象并执行
- 如果构造函数返回对象,则返回该对象;否则返回新对象
手写 new
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype)
const result = Constructor.apply(obj, args)
return result instanceof Object ? result : obj
}
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayHi = function () {
console.log('Hi, ' + this.name)
}
const p = myNew(Person, 'Tom', 25)
p.sayHi()
构造函数返回值的影响
function Foo() {
this.name = 'foo'
return { name: 'bar' }
}
new Foo().name
function Bar() {
this.name = 'bar'
return 'string'
}
new Bar().name
同分类其他题目