javascript安全类型检测(判断是否是原生对象)

来源:互联网 发布:linux主机 编辑:程序博客网 时间:2024/05/17 04:56

typeof的小”bug”;

提到类型检测大家首先应该会想到typeof 操作符,现在复习一下她的用法,对于一个值使用typeof会得到以下结果:
“undefined”,”boolean”,”string”,”number”,”object”,”function”;
但是,有个bug是,当值为正则表达式的时候,结果为”function”;


instanceof的弊端:

value instanceof Array
以上表达式要为true的条件是,value必须是一个数组,并且还要和Array在同一个全局作用域;

利用Object.prototype.toString();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString 中对toString方法的解释:

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns “[object type]”, where type is the object type. The following code illustrates this

意思是任何值在调用原声Object的toString方法,多会返回[object type]”

var o = new Object();o.toString(); // returns [object Object]

举个例子:

var a = [1,3];var type = Object.prototype.toString.call(a);console.log(type);//[object Array] console.log(a.toString());//'4 1,3';

上述代码第一次调用的是原生toString方法,而第二次调用的是Array的toString方法;
所以借助以上原理,我们可以设计出判断是否是原声函数、原声正则表达式等方法:

function isFunction(value){   return Object.prototype.toString.call(value) == '[Object Function]';}function isRegExp(value){   return Object.prototype.toString.call(value) == '[Object RegExp]';}function isJSON(value){//判断是否是原生JSON对象   return Object.prototype.toString.call(value) == '[Object JSON]';}
阅读全文
0 0
原创粉丝点击