我是靠谱客的博主 正直世界,这篇文章主要介绍JS学习笔记—使用instanceof判断原始类型,现在分享给大家,希望可以做个参考。

问题提出:

复制代码
1
2
3
4
5
var str = 'hello world' str instanceof String // false var str1 = new String('hello world') str1 instanceof String // true

问题解决:

复制代码
1
2
3
4
5
6
class PrimitiveString { static [Symbol.hasInstance](x) { return typeof x === 'string' } } console.log('hello world' instanceof PrimitiveString) // true

问题解析:

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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。

 

最后

以上就是正直世界最近收集整理的关于JS学习笔记—使用instanceof判断原始类型的全部内容,更多相关JS学习笔记—使用instanceof判断原始类型内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部