4.1 Typeof

可以判断基本类型数据类型,除了null以外

  1. typeof 1 // 'number'
  2. typeof '1' // 'string'
  3. typeof undefined // 'undefined'
  4. typeof true // 'boolean'
  5. typeof Symbol() // 'symbol'
  6. typeof b // b 没有声明,但是还会显示 undefined

在判断引用类型时,除了function其他都会返回object

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

在判断null的时候会返回object,这是存在一个很久的bug

  1. typeof null // 'object'

出在这个bug的原因是JavaScript创立之初使用的操作系统是32位操作系统,为了性能使用的低位存储, 000 开头表示为对象,而 null 全是零,所以会返回 object

4.2 instanceof

instanceof 可以正确的判断对象的类型,其内部机制是通过判断对象的原型链中能不能找到其对象构造函数或对象的 prototype

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

手动实现:

  1. function instaceOf(left, right) {
  2. let proto = left.__proto__
  3. let prototype = right.prototype
  4. while(true) {
  5. if (proto === null) {
  6. return false
  7. }
  8. if (proto === prototype) {
  9. return true
  10. }
  11. proto = proto.__proto__
  12. }
  13. }

4.3 Object.prototype.toString.call()

可以利用toString()方法返回的字符串正确判断数据的类型,不论是基本类型数据还是引用类型数据,最为靠谱的方法。

  1. function getType(obj) {
  2. const strs = Object.prototype.toString.call(obj).split(' ')
  3. if (strs.length > 1) {
  4. let typeStr = strs[1]
  5. typeStr = typeStr.substring(0, typeStr.length - 1)
  6. return typeStr.toLowerCase()
  7. }
  8. }
  9. getType({}) // object
  10. getType('a') // string
  11. getType(true) // boolean
  12. getType(1) // number
  13. getType(null) // null