Class checking: "instanceof"

instanceof 檢測物件數否屬於 class 包含繼承

The instanceof operator

// syntax
obj instanceof Class

// 返回布林值
class Rabbit {}
let rabbit = new Rabbit();

// is it an object of Rabbit class?
alert( rabbit instanceof Rabbit ); // true

// 也可以檢測建構函式
// instead of class
function Rabbit() {}

alert( new Rabbit() instanceof Rabbit ); // true

// 內建 class 也可以
let arr = [1, 2, 3];
alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true

// 自己設定 instanceof 
// setup instanceOf check that assumes that anything that canEat is an animal
class Animal {
  static [Symbol.hasInstance](obj) {
    if (obj.canEat) return true;
  }
}

let obj = { canEat: true };

alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called

// 大多數 class 沒有 Symbol.hasInstance,因此會找物件原型鏈
obj.__proto__ === Class.prototype
obj.__proto__.__proto__ === Class.prototype
obj.__proto__.__proto__.__proto__ === Class.prototype
...

// example
class Animal {}
class Rabbit extends Animal {}

let rabbit = new Rabbit();
alert(rabbit instanceof Animal); // true
// rabbit.__proto__ === Rabbit.prototype
// rabbit.__proto__.__proto__ === Animal.prototype (match!)

// 原型被改變 instanceof 找不到 
function Rabbit() {}
let rabbit = new Rabbit();

// changed the prototype
Rabbit.prototype = {};

// ...not a rabbit any more!
alert( rabbit instanceof Rabbit ); // false

Bonus: Object.prototype.toString for the type

Last updated

Was this helpful?