原文:The instanceof Operator in JavaScript
instanceof运算符可以确定一个对象是否是一个类的实例。
instanceof运算符可以判断一个对象是否是某个JavaScript类的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | class Rectangle {   constructor(height, width) {     this.height = height;     this.width = width;   } }
  const obj = new Rectangle(3, 5); obj.height;  obj.width; 
 
  obj instanceof Rectangle;  ({}) instanceof Rectangle; 
  | 
 
技术上来讲,instanceof运算符检查对象的原型链,看原型链上有没有constructor等于给定的类。这样,如果存在继承关系,子类的实例同样也是基类的一个实例。
1 2 3 4 5 6 7
   | class BaseClass {} class SubClass extends BaseClass {}
  const obj = new SubClass();
  obj instanceof SubClass;  obj instanceof BaseClass; 
  | 
 
Object类
Object类是所有JavaScript类的基类。
1 2 3 4 5 6 7
   | class MyClass {}
  const obj = new MyClass();
  obj instanceof Object;  ({}) instanceof Object;  null instanceof Object; 
  | 
 
你可能会想到用v instanceof Object检查v是否是对象。在大部分场景是可行的,但在某些情况下对象不是Object的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13
   | 
 
  typeof Object.prototype;  Object.prototype instanceof Object; 
 
 
  function MyClass() {} MyClass.prototype = Object.create(null);
  typeof new MyClass();  (new MyClass()) instanceof Object; 
 
  | 
 
异常情况
instanceof运算符在右侧不是函数时会抛出错误。
译注:函数的判断依据是typeof a === 'function',ES6的类也是函数
1 2 3 4 5 6 7 8 9 10 11
   | class MyClass {}
  function MyOtherClass() {}
  const obj = {};
  obj instanceof MyClass;  obj instanceof MyOtherClass; 
 
  obj instanceof { answer: 42 };
  |