当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js安全类型检测

js安全类型检测

2019年08月01日  | 移动技术网IT编程  | 我要评论

背景: 都知道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 模拟实现:

 1  function instanceof(left, right) {
 2       let leftvalue = left.__proto__
 3       let rightvalue = right.prototype
 4        console.log(leftvalue,rightvalue)
 5        while (true) {
 6          if (leftvalue === null) {
 7           return false
 8          }
 9          if (leftvalue === rightvalue) {
10            return true
11         }
12         leftvalue = leftvalue.__proto__
13       }
14      }
15 
16      let a = {};
17 
18      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"

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网