- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew.ts
43 lines (38 loc) · 961 Bytes
/
new.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @description 实现一个new方法
* @author tangc1
* @date 2022-04-21 21:05:52
*/
exportfunctioncustomNew<T>(constructor: Function, ...args: any[]): T{
// 1. 创建一个空对象,继承constructor的原型
constobj=Object.create(constructor.prototype)
// 2. 将obj作为this,执行constructor,并传入参数
constructor.apply(obj,args);
// 3. 返回obj
returnobj
}
classFoo{
name: string
age: number
city: string
constructor(name: string,age: number,city: string){
this.name=name
this.age=age
this.city=city
}
getName(){
returnthis.name
}
getAge(){
returnthis.age
}
getCity(){
returnthis.city
}
}
// const f = new Foo('zhangsan', 18, 'changsha')
constf=customNew<Foo>(Foo,'zhangsan',18,'changsha')
console.info(typeoff);
console.info(typeofFoo);
console.info(f);
console.info(f.getCity());