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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41144066/article/details/89375491

问题提出:

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。

猜你喜欢

转载自blog.csdn.net/weixin_41144066/article/details/89375491