instanceof机制和实现

129 阅读1分钟

1. instanceof机制

  1. 获取对象的__proto__和判断类型的prototype
  2. 遍历对象上的所有原型直到==判断类型的prototype返回true
  3. 若遍历到尽头也就是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
  }
}