instanceof机制和实现

7/21/2022 js

# 1. instanceof机制

  1. 获取对象的__proto__和判断类型的prototype
  2. 遍历对象上的所有原型直到==判断类型的prototype返回true
  3. 若遍历到尽头也就是null了还是没结果返回false
function instanceof(left, right) {
  for (left = left.__proto__; left; left = left.__proto__) {
    if (left === right.prototype) return true
  }
  return false
}

# 2. [Symblol.hasInstance]方法重写

更精确的来说a instanceof B实际会执行B[Symbol.hasInstance](a)

// instanceof机制
class A {
  static [Symbol.hasInstance](instance){
    for(instance = instance.__proto; instance; instance = instance.__proto__){
      if(instance === this) return true
    }
    return false
  }
}
new A() instanceof A // true

// 重写
class Person{ 
  static [Symbol.hasInstance](instance){ 
    return instance instanceof Array 
  } 
} 

[1,2,3] instanceof Person // true
new Person() instanceof Person // false
    我想,
    在这个世界上,
    虽然没有最美好的相遇,
    但却应该有为了相遇或重逢,
    所做的最美好的努力。
    红莲华
    x
    loading...