JS中的 typeof 和 instanceof

328 阅读1分钟

typeof 对于原始类型来说,除了 null 之外都可以显示正确的类型

typeof 1            // 'number'
typeof '1'          // 'string'
typeof undefined    // 'undefined'
typeof true         // 'boolean'
typeof Symbol()     // 'symbol'

typeof 对于对象来说,除了函数之外都会显示 object,所以说 type 并不能准确判断变量到底是什么类型

typeof []           // 'object'
typeof {}           // 'object'
typeof console.log  // 'function'

如果想判断一个对象的正确类型,这时候可以考虑使用 instanceof,因为内部机制是通过原型链来判断的

const Person = finction() {};
const p1 = new Person();
p1 instanceof Person // true

let say = 'hello world';
say instanceof String // false

let say2 = new String('hello world');
say2 instanceof String // true

对于原始类型来说,直接通过 instanceof 来判断类型是不行的,但还是有办法让 instanceof 判断原始类型的

class PrimitiveString {
  static [Symbol.hasInstance](x) {
    return typeof x === 'string'
  }
}

console.log('hello world' instanceof PrimitiveString) // true

Symbol.hasInstance 是一个能自定义 instanceof 行为的存在,以上代码等同于 typeof 'hello world' === 'string',所以结果为true。但其实侧面反映了一个问题,instanceof 也不是百分之百可信的。

---END---