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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值