new
关键字会进行如下的操作:
{}
);this
的上下文 ;this
。 function createNew (constructor, ...args) {
// 创建一个空对象
const obj = {}
// 链接原型(__proto__写法已经废弃)
// obj.__proto__ = constructor.prototype
Object.setPrototypeOf(obj, constructor.prototype)
// 改变 this 指向,把constructor的 this 绑定到 obj 上,此时 obj 就继承了 constructor 的属性和方法
const result = constructor.apply(obj, args)
// 如果没有返回对象,则返回 this
return typeof result === 'object' ? result : obj
}
function People(name,age) {
this.name = name
this.age = age
}
let peo = createNew(People, 'Shaoli', 28)
console.log(peo.name) // Shaoli
console.log(peo.age) // 28
如果有返回结果的
function People2 (name, age) {
this.name = name
return {
name: this.name
}
}
let peo2 = createNew(People, 'Shaoli', 28)
console.log(peo2) // {name: "Shaoli"}
如有不足,麻烦指出!
©2018-2020 hongshali.com 版权所有 ICP证:闽ICP备18029655号-1