使用 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章