definition
The instanceof operator is used to test whether the constructor's prototype property appears anywhere in the object's prototype chain. ——MDN
Simply understood as: instanceof
you can detect whether an instance belongs to a certain type.
function Foo(){
}
const a = new Foo()
a instanceof Foo // true
a instanceof Object // true
It can also be used in inheritance relationships to determine whether an instance belongs to its parent type.
function Foo(){
}
function Child(){
}
function Other(){
}
Child.prototype = new Foo // 继承原型
const b = new Child()
b instanceof Foo // true
b instanceof Child // true
b instanceof Other // false
b instanceof Object // true
accomplish
prototype
Check whether the object pointed to by object B is prototype
on the [[ ]] chain of object A.
If it is, return it true
, if it is not, return it false
. However, there is a special case, when the object B prototype
will null
report an error (similar to a null pointer exception).
Function mocking A instanceof B:
/**
* @param obj{Object} 测试对象
* @param fun{Function} 构造函数
*/
function instanceOf(A, B) {
let obj = A.__proto__
let fn = B.prototype
while (true) {
if (obj === null) return false
// 这里重点:当 fn 严格等于 obj 时,则返回 true
if (fn === obj) return true
obj = obj.__proto__
}
}