Skip to content

instanceof

检查一个 对象 是否属于某个 class。

js
// function Rabbit() {}
class Rabbit {}

new Rabbit() instanceof Rabbit; // true

考虑了继承:

js
let arr = [1, 2, 3];
arr instanceof Array; // true
arr instanceof Object; // true

instanceof 大致算法

js
obj instanceof Class;
  1. Class 有静态方法 Symbol.hasInstance 直接调用
  2. 检测原型链。obj.__proto__ === Class.prototype

Symbol.hasInstance

js
class Animal {
  static [Symbol.hasInstance](obj) {
    if (obj.canEat) return true;
  }
}

Object.isPrototypeOf

js
objA.isPrototypeOf(objB);

如果 objA 处在 objB 的原型链中,则返回 true

中途修改

Class 的 constructor 自身是不参与 instanceof 检查的!检查过程只和 原型链 以及 Class.prototype 有关。

obj.__proto__ === Class.prototype?
obj.__proto__.__proto__ === Class.prototype?
obj.__proto__.__proto__.__proto__ === Class.prototype?
js
function Rabbit() {}
let rabbit = new Rabbit();

// 修改了 prototype
Rabbit.prototype = {};

// ...再也不是 rabbit 了!
rabbit instanceof Rabbit; // false
rabbit.constructor == Rabbit; // true