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

[javascript] view plaincopyprint?
 
  1.    op = Object.prototype,  
  2.    ostring = op.toString,  
  3. ...  
  4.   
  5. function isFunction(it) {  
  6.         return ostring.call(it) === '[object Function]';  
  7.     }  
  8.   
  9.     function isArray(it) {  
  10.         return ostring.call(it) === '[object Array]';  
  11.     }  


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

typeof

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

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 "]".  
[javascript] view plaincopyprint?
 
    1. var oP = Object.prototype,  
    2. toString = oP.toString;  
    3.   
    4. console.log(toString.call([123]));//[object Array]  
    5. console.log(toString.call('123'));//[object String]  
    6. console.log(toString.call({a: '123'}));//[object Object]  
    7. console.log(toString.call(/123/));//[object RegExp]  
    8. console.log(toString.call(123));//[object Number]  
    9. console.log(toString.call(undefined));//[object Undefined]  
    10. console.log(toString.call(null));//[object Null]  
    11. //....  
原文地址:https://www.cnblogs.com/xuan52rock/p/4378824.html