使用 instanceof 判断数据类型

instanceof:的作用就是检测构造函数的 prototype 和 实例的原型__proto__是否相等。

  • String 和 Date 对象同时也属于Object 类型
    console.log(String.prototype.__proto__ === Object.prototype) // true
    console.log(Date.prototype.__proto__ === Object.prototype)  // true
  • 如果通过 字面量 的方式创建字符串,那么无法通过 instanceof 判断某个变量是否是字符串
    let str2 = 'aaaa'
    console.log(str2 instanceof String) // false
    console.log(str2 instanceof Object) // false
  • 通过 new 方式,是可以使用 instanceof 判断 变量是否是字符串。
    let str1 = new String('aaa')
    console.log(str1 instanceof String) // true
    console.log(str1 instanceof Object) // true
    console.log(str1.__proto__ === String.prototype) // true
  • 对于复杂数据类型 对象 和 数组,无论是通过字面量的方式创建,还是 new 的方式,都是可以通过 instanceof 来判断数据类型的
class Dog {
  constructor(name) {
    this.name = name
    this.type = 'dog'
  }
}

let d1 = new Dog('大黄')
let d2 = { name: '肉肉' }
console.log(d1)  //  { name: '大黄', type: 'dog' }
console.log(d2) // { name: '肉肉' }
console.log(d1 instanceof Dog)  // true
console.log(d1 instanceof Object) // true
console.log(d2 instanceof Object)  // true

let arr1 = [1, 2]
let arr2 = new Array('a', 'b')
console.log(arr1 instanceof Array) // true
console.log(arr2 instanceof Array) // true