1. instanceof机制
- 获取对象的
__proto__和判断类型的prototype - 遍历对象上的所有原型直到==判断类型的
prototype返回true - 若遍历到尽头也就是
null了还是没结果返回false
// a instanceof A
function _instanceof(a, A) {
for (a = a.__proto__; a; a = a.__proto__) {
if (l === A.prototype) return true
}
return false
}
2. instanceof本质
更精确的来说,a instanceof A 实际执行的是 A[Symbol.hasInstance](a)
class A {
static [Symbol.hasInstance](a) {
for (a = a.__proto__; a; a = a.__proto__) {
if (l === A.prototype) return true
}
return false
}
}