js安全类型检测
背景:
都知道js内置的类型检测,大多数情况下是不太可靠的,例如: typeof 、 instanceof。
typeof 返回一个未经计算的操作数的类型, 可以发现所有对象都是返回object (null是空指针即空对象)

instanceof : 用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置 (简单理解: 左侧检测的对象是否可以沿着原型链找到与右侧构造函数原型属性相等位置) 后面会附上模拟方法。
缺点:
1、instanceof 与全局作用域有关系,[] instanceof window.frames[0].Array 会返回false,因为 Array.prototype !== window.frames[0].Array.prototype
2、Object派生出来的子类都是属于Obejct [] instanceof Array [] instanceof Object 都是true
instanceof 模拟实现:
function instanceOf(left, right) {
let leftValue = left.__proto__
let rightValue = right.prototype
console.log(leftValue,rightValue)
while (true) {
if (leftValue === null) {
return false
}
if (leftValue === rightValue) {
return true
}
leftValue = leftValue.__proto__
}
}
let a = {};
console.log(instanceOf(a, Array))安全类型检测方法:
任何值上调用 Object 原生的 toString()方法,都会返回一个[object NativeConstructorName]格式的字符串。
NativeConstructorName ===> 原生构造函数名 (即是它爸的名字,并非爷爷(Object)的名字)
function isArray(value){
return Object.prototype.toString.call(value) == "[object Array]";
}
function isFunction(value){
return Object.prototype.toString.call(value) == "[object Function]";
}
function isRegExp(value){
return Object.prototype.toString.call(value) == "[object RegExp]";
}为啥直接用实例对象的toString方法不可以呢? 这是因为在其他构造函数下,将toString方法进行了重写。 例如: [1,2].toString() ===> "1,2"
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!