-
Notifications
You must be signed in to change notification settings - Fork 7
/
instanceof.ts
74 lines (59 loc) · 1.37 KB
/
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// * ================================================================================ original
{
class A {}
class B extends A {}
class C extends B {}
class D extends B {}
class E extends A {}
/*
A <- B <- C
B <- D
A <- E
*/
// * ----------------
const inst = new C();
console.warn([
inst instanceof Object,
inst instanceof A,
inst instanceof B,
inst instanceof C,
inst instanceof D,
inst instanceof E,
]);
}
console.log('--------');
// * ================================================================================ our
// * 只要理解了 ES 的继承中,继承类的 prototype 是基类的实例
{
const instanceOf = (proto: any, inst: any) => {
let p = inst;
const p0 = proto.prototype;
if (p0 === undefined) throw TypeError(`instanceof ${proto} is not callable`);
while (p !== null) {
if (p === p0) return true;
p = Object.getPrototypeOf(p);
}
return false;
};
// * ----------------
class A {}
class B extends A {}
class C extends B {}
class D extends B {}
class E extends A {}
/*
A <- B <- C
B <- D
A <- E
*/
// * ----------------
const inst = new C();
console.warn([
instanceOf(Object, inst),
instanceOf(A, inst),
instanceOf(B, inst),
instanceOf(C, inst),
instanceOf(D, inst),
instanceOf(E, inst),
]);
}