instanceof判断问题

有时候我们根据instanceof来判断对象的数据类型

但是 用instanceof判断基本数据类型时 会不靠谱

例如

let str = '123'

let str1 = new String("123")

console.log(str instanceof String)  //false

console.log(str1 instanceof String ) //true

这时候,可以重写instanceof的判断规则

class typeofString{

  static [Symbol.hasInstance](x){

    return typeof str === "string"    

  }

}

console.log(str typeof typeofString)  //true

posted @ 2020-03-27 12:18  小白白又白啦  阅读(499)  评论(0编辑  收藏  举报