typeof和instanceof都是判断数据类型的,但是他们有什么区别呢,今天我们就来看一看:
typeof
对于原始类型来说,除了 null
都可以显示正确的类型:
复制代码
1
2
3
4
5
6typeof 1 // 'number' typeof '1' // 'string' typeof undefined // 'undefined' typeof true // 'boolean' typeof Symbol() // 'symbol'
但是有一点,typeof
对于对象来说,除了函数都会显示 object
,所以说 typeof
并不能准确判断变量到底是什么类型:
复制代码
1
2
3
4typeof [] // 'object' typeof {} // 'object' typeof console.log // 'function'
如果这个时候我们想判断一个对象的正确类型,这时候可以考虑使用 instanceof
,因为它内部机制是通过原型链来判断的:
复制代码
1
2
3
4
5
6
7
8
9
10const Person = function() {} const p1 = new Person() p1 instanceof Person // true var str = 'hello world' str instanceof String // false var str1 = new String('hello world') str1 instanceof String // true
对于原始类型来说,你想直接通过 instanceof
来判断类型是不行的,当然还是有办法让 instanceof
判断原始类型的:
复制代码
1
2
3
4
5
6
7class PrimitiveString { static [Symbol.hasInstance](x) { return typeof x === 'string' } } console.log('hello world' instanceof PrimitiveString) // true
这里的Symbol.hasInstance
是什么东西?其实就是一个能让我们自定义 instanceof
行为的东西,以上代码等同于 typeof 'hello world' === 'string'
,所以结果自然是 true
了。
最后
以上就是谨慎心情最近收集整理的关于浅谈typeof和instanceof的全部内容,更多相关浅谈typeof和instanceof内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复