JS学习笔记—使用instanceof判断原始类型

问题提出:

var str = 'hello world'
str instanceof String // false

var str1 = new String('hello world')
str1 instanceof String // true

问题解决:

class PrimitiveString {
  static [Symbol.hasInstance](x) {
    return typeof x === 'string'
  }
}
console.log('hello world' instanceof PrimitiveString) // true

问题解析:

1、static定义的是类的静态方法,使用instanceof时会默认调用

2、当同时定义静态方法和动态方法时:

class MyClass {
  [Symbol.hasInstance](foo) {
    return foo instanceof Array;
  }

  static [Symbol.hasInstance](obj) {
    return Number(obj) % 2 === 0;
  }
}
var x = new MyClass()
console.log([1, 2, 3] instanceof new MyClass()); // true //我是调用的动态方法

console.log(x[Symbol.hasInstance]([0, 0, 0,]));//true //我是调用的动态方法

console.log(2 instanceof MyClass); //true 我是调用静态方法

console.log(MyClass[Symbol.hasInstance](2));//true 我是调用了静态方法

console.log(x instanceof MyClass); //false 因为修改了静态方法。x本身就是MyClass的实例,如果注释了静态方法就会返回true。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值