1、创建一个空对象obj,继承构造函数的原型
2、执行构造函数(将obj作为this)
3、返回obj
function customNew<T>(constructor:Function, ...args:any[]):T {
// 1、创建一个空对象,继承constructor的原型,不能直接const obj= {} 原型指向就错了
const obj = Object.create(constructor.prototype)
// 2、将obj作为this,执行constructor,传入参数
constructor.apply(obj,args)
// 3、返回obj
return obj
}
// 实例
class Foo {
name: string
age:number
constructor(name: string) {
this.name = name
this.age = 50
}
getName(){
return this.name
}
}
const f = new Foo('zhangsan')
const f1 = customNew<Foo>(Foo,'zhangsan')
Object.create 和直接{}有什么区别?
1、{}创建空对象,原型指向Object.prototype
2、Object.create是创建空对象,原型指向传入的参数
const obj1 = {}
obj1.__proto__ === Object.prototype // true
const obj = {x:100}
const obj2 = Object.create(obj)
obj2.__proto__ === obj // true