手写instanceof
首先写之前要先理解一下instanceof的实现原理:
- instanceof 主要的实现原理就是只要右边变量的prototype在左边变量的原型链上即可(也就是说左边的变量能在原型链上找到左边变量的prototype)
了解原理之后开始看代码:
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
| function myInstanceOf(left, right) { let rightVal = right.prototype let leftVal = left.__proto__ while (true) { if (leftVal === null) { return false } if (leftVal === rightVal) { return true } leftVal = leftVal.__proto__ } }
function Test() { } let test = new Test(); console.log(myInstanceOf(test, Test));
------------------ 结果: true
|
总结:
instanceof在查找的过程中会遍历左边变量的原型链,直到找到右边变量的 prototype,如果查找失败,则会返回 false.