- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstanceof.ts
29 lines (24 loc) · 785 Bytes
/
instanceof.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
/**
* @description instanceof
* @author tangc1
* @date 2022-04-23 14:38:54
*/
exportfunctionmyInstanceof(instance: any,origin: any): boolean{
if(instance==null)returnfalse// null undefined
consttype=typeofinstance
// 值类型
if(type!=='object'&&type!=='function')returnfalse
lettempInstance=instance// 防止修改instance
while(tempInstance){
if(tempInstance.__proto__===origin.prototype){
// 匹配上
returntrue
}
tempInstance=tempInstance.__proto__// 顺着原型链往上找
}
returnfalse
}
console.info(myInstanceof({},Object));
console.info(myInstanceof([],Object));
console.info(myInstanceof([],Array));
console.info(myInstanceof('abc',String));