首页 > 其他 > 详细

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

时间:2015-04-15 11:00:24      阅读:131      评论:0      收藏:0      [点我收藏+]

为什么类型判断用到Object.prototype.toString.call()进行类型判断,而不用typeof()呢?

然后翻了一下资料:

Typeof

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

Object.prototype.toString.call():

 

ECMA 对Object.prototype.toString的解释

 

  1. Object.prototype.toString ( )  
  2.   
  3. When the toString method is called, the following steps are taken:  
  4.   
  5. If the this value is undefined, return "[object Undefined]".  
  6. If the this value is null, return "[object Null]".  
  7. Let O be the result of calling ToObject passing the this value as the argument.  
  8. Let class be the value of the [[Class]] internal property of O.  
  9. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".   

然后举了个例子:

 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]  

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

原文:http://www.cnblogs.com/duyao/p/4427763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!