-
typeof的区别:
typeof在对原始类型类型number、string、boolean 、null 、 undefined、 以及引用类型的function的反应是精准的;
但是,对于对象{ } 、数组[ ] 、null 都会返回object
为了弥补这一点,instanceof 从原型的角度,来判断某引用属于哪个构造函数,从而判定它的数据类型。
-
instanceof 的作用
用于判断一个引用类型是否属于某构造函数(用于检测构造函数的原型是否出现在某个实例函数的原型链上);
还可以在继承关系中用来判断一个实例是否属于它的父类型
-
最好的方法是使用
Object.prototype.toString方法,它可以检测到任何类型,返回的结果是[object Type]的形式,基本可以实现所有类型的检测,我们用下面的代码来演示一下。
//实现一个检测类型的公共接口
function detectType(type) {
return function(obj) {
return {}.toString.call(obj) === `[object ${type}]`
}
}
//根据自己的需求进行扩展,记住类型的首字母要大写
const isArray = detectType("Array")
const isFunc = detectType("Function")
const isRegExp = detectType("RegExp")
console.log(isArray([1, 2, 3])); //true
console.log(isArray("[1,2,3]")); //false
console.log(isFunc(detectType)); //true
console.log(isRegExp(/test/)); //true
参考: