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

猜你喜欢

转载自www.cnblogs.com/vnwith/p/12580524.html