前端基础进阶(十八) : typeof vs instanceof vs ...
文章目录
typeof 是否能正确判断类型?instanceof 能正确判断对象的原理是什么?
typeof对于原始类型来说,除了null都可以显示正确的类型
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'typeof对于对象来说,除了函数都会显示object,所以说typeof并不能准确判断变量到底是什么类型
typeof [] // 'object'
typeof {} // 'object'
typeof null // 'object'
typeof console.log // 'function'instanceof操作符用来判断是否当前对象是特定类的对象。
如果我们想判断一个对象的正确类型,这时候可以考虑使用instanceof,因为内部机制是通过原型链来判断的,在后面的章节中我们也会自己去实现一个instanceof。并且所有对象类型 instanceof Object 都是 true。
const 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 Array; // true
[] instanceof Object; // true
对于原始类型来说,你想直接通过instanceof来判断类型是不行的,当然我们还是有办法让instanceof判断原始类型的
class PrimitiveString {
static [Symbol.hasInstance](x) {
return typeof x === 'string'
}
}
console.log('hello world' instanceof PrimitiveString) // true你可能不知道Symbol.hasInstance是什么东西,其实就是一个能让我们自定义instanceof行为的东西,以上代码等同于typeof 'hello world' === 'string',所以结果自然是true了。这其实也侧面反映了一个问题,instanceof也不是百分之百可信的。
总结:
typeof对于原始类型来说,除了null都可以显示正确的类型。typeof对于对象来说,除了函数都会显示object,所以说typeof并不能准确判断引用类型到底是什么类型。
instanceof只能用来判断对象类型,原始类型不可以(大概是基本类型没有原腥链)。并且所有对象类型 instanceof Object 都是 true。
Array.isArray()ES5新增判断是否为数组方法
Object.prototype.toString.call()判断类型都试用
参考网址:
学习如何判断数据类型
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论