手写 new
思路: 参数(fn,..args)
- object.create 绑定 fn 的共有属性
- 调用绑定 fn 自身属性
- 检查类型返回对象
function myNew(fn,...args) {
// 继承共有属性:绑定原型
// newObj.__proto__ = fn.prototype
const newObj = Object.create(fn.prototype) // 方法用于创建一个新对象,使用现有的对象来作为新创建对象的原型(prototype)。
// 继承自身属性(改变this指向),同时把参数传入
const result = fn.apply(newObj,args)
// 检查return类型
return typeof result === 'object' ? result : newObj
}
使用方法:
function 士兵(id) {
// 自身属性
this.id = id
}
// 共有属性
士兵.prototype.run = function () {
/*走俩步的代码*/
}
const 士兵1 = myNew(士兵, '1') // 等价于const 士兵1 = new 士兵('1')
console.log(士兵1)