instanceof

110 阅读1分钟

instanceof 用来检测一个对象是否是一个类的实例

  • instanceof 检查的是对象原型链上是否有该实例,只要原型链上有该类实例,就会返回true。
  • Object 是所有对象的原型,所以在任何对象和Object进行 instanceof 运算都会返回 true。
class Animal{}

class Dog extends Animal{}

const dog = new Dog()

console.log(dog instanceof Dog) // true
console.log(dog instanceof Animal) // true
console.log(dog instanceof Object) // true

// dog --> Animal实例 --> Object实例 --> Object原型