instanceOf 被问到的频率太高了,记录一波
1. 是什么
在 MDN 上是这样描述 instanceof 的:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
instanceof
运算符用于测试构造函数的 prototype 属性是否出现在对象原型链中的任何位置
2. 实现
这里已经描述的很清楚了, 怎么实现呢
思路:
- 首先
instanceof
左侧必须是对象, 才能找到它的原型链
instanceof
右侧必须是函数, 函数才会prototype
属性
- 迭代 , 左侧对象的原型不等于右侧的
prototype
时, 沿着原型链重新赋值左侧
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const instance_of = (left, right) => { const baseType = ['number', 'string', 'boolean', 'undefined', 'symbol'] if (baseType.includes(typeof left)) return false const RP = right.prototype while (true) { if (left === null) { return false } else if (left === RP) { return true } left = left.__proto__ } }
|
3. 需要注意的一些情况
以下状况均为 false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
'abc' instanceof String
null instanceof Object
String instanceof String Number instanceof Number
|
-
版权声明: 本博客所有文章除特别声明外,均采用
CC BY 4.0 CN协议
许可协议。转载请注明出处!
Жизнь, как качели - то вверх, то вниз.