手写instanceof

手写instanceof

1
2
3
4
5
6
7
8
9
10
11
12
13
function myInstance(obj1, obj2) {
let obj1Proto = obj1.__proto__;
while(true) {
// null.__proto__为空
if (obj1Proto == null) {
return false;
}
if (obj1Proto == obj2.prototype) {
return true;
}
obj1Proto = obj1Proto.__proto__;
}
}
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
class Person{
constructor(name, age) {
this.name = name;
this.age = age;
}
}
// 子类继承
class Student extends Person {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;
}
}
function myInstance(obj1, obj2) {
let obj1Proto = obj1.__proto__;
while(true) {
// null.__proto__为空
if (obj1Proto == null) {
return false;
}
if (obj1Proto == obj2.prototype) {
return true;
}
obj1Proto = obj1Proto.__proto__;
}
}
// 实例化
const zhangsan = new Student("张三",18,"男");
console.log(myInstance(zhangsan, Student)); // true
console.log(myInstance(zhangsan, Person)); // true
console.log(myInstance(zhangsan, Object)); // true
console.log(myInstance(zhangsan, Array)); // false

手写instanceof
http://example.com/2023/04/13/07.前端小课堂/10.手写instanceof/
作者
Deng ErPu
发布于
2023年4月13日
许可协议