1. 语法上的不同

  1. // typeof
  2. typeof 123 // Number
  3. // instanceof
  4. function Car(make, model, year) {
  5. this.make = make;
  6. this.model = model;
  7. this.year = year;
  8. }
  9. const auto = new Car('Honda', 'Accord', 1998);
  10. console.log(auto instanceof Car); // true
  11. console.log(auto instanceof Object); // true

2. 本质上的不同

2.1 typeof

  1. typeof 是针对变量自身,返回一个字符串,表示当前变量的类型;
  2. typeof 对复杂数据返回都是 ‘object’,无法区分数组,对象,函数,同时 typeof null === ‘object’;

    instanceof

  3. instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上;所以它可以准确的判断变量的类型;

  4. 但是对于基本数据类型,无法判断通过字面量方式创建的类型,只能通过 new 的形式创建的类型。
  1. var str1 = '这是一个字符串'
  2. var str2 = new String('这是一个字符串')
  3. str1 instanceof String // false
  4. str2 instanceof String // true