Object.prototype.toString.call()进行类型判断

   op = Object.prototype,
   ostring = op.toString,
...

function isFunction(it) {
        return ostring.call(it) === '[object Function]';
    }

    function isArray(it) {
        return ostring.call(it) === '[object Array]';
    }

最近在看requireJS的源码时,看到上面一段代码,很是好奇,为啥进行类型判断时使用Object.prototype.toString? 如果是我的话就直接用typeof得了,后来查阅了一些资料:


typeof

在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。


ECMA 对Object.prototype.toString的解释

Object.prototype.toString ( )

When the toString method is called, the following steps are taken:

If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2


var oP = Object.prototype,
toString = oP.toString;

console.log(toString.call([123]));//[object Array]
console.log(toString.call('123'));//[object String]
console.log(toString.call({a: '123'}));//[object Object]
console.log(toString.call(/123/));//[object RegExp]
console.log(toString.call(123));//[object Number]
console.log(toString.call(undefined));//[object Undefined]
console.log(toString.call(null));//[object Null]
//....


参考:http://my.oschina.net/sfm/blog/33197

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值