js 实现 instanceof

本文最后更新于 2024年4月26日 下午

instanceof 实现原理, 只要右边表达式的 prototype 在左边的原型之上。因此 instanceof 在查找过程中会遍历左边的变量的原型链,直至找到右边变量的 prototype 为止,如果找到 返回 true, 如果查找失败则返回 false

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function instanceof(left, right) {
// 取右边表达式的原型 prototype
let rightPrototype = right.prototype
// 取左边表达式的 原型链 __proto__
left = left.__proto__

while(true) {
if (left === null) {
return false
}
if (rightPrototype === left) {
return true
}
left = left.__proto__
}
}

我们来举一个例子🌰

1
2
3
4
5
6
7
8
function Foo() {}

Object instanceof Object; // true
Function instanceof Function; // true
Function instanceof Object; // true
Foo instanceof Foo; // false
Foo instanceof Object; // true
Foo instanceof Function; // true

原型图解:


js 实现 instanceof
https://dev.dgdream.online/2024/04/26/js 实现 instanceof/
作者
执念
发布于
2024年4月26日
更新于
2024年4月26日
许可协议