首先看一段ECMA中对Object.prototype.toString的解释:
Object.prototype.toString( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)
我们知道,Javascript中,一切皆为对象。所以如下代码,应当会输出对应字符:
01 | var oP = Object.prototype, |
02 | toString = oP.toString; |
04 | console.log(toString.call([123])); |
05 | console.log(toString.call( '123' )); |
06 | console.log(toString.call({a: '123' })); |
07 | console.log(toString.call(/123/)); |
08 | console.log(toString.call(123)); |
09 | console.log(toString.call(undefined)); |
10 | console.log(toString.call( null )); |
标准浏览器中完美的作到,但是(为什么要说但是呢)IE6中,却会出现以下问题:
通过Object.prototype.toString.call获取的 字符串,undefined,null均为Object
所以,我们又要悲剧的先对以上类型进行判断,完整代码:
01 | var oP = Object.prototype, |
02 | toString = oP.toString; |
04 | function typeOf(value) { |
09 | var type = typeof value; |
10 | if ( 'undefined' === type || 'string' === type) { |
14 | var typeString = toString.call(value); |
16 | case '[object Array]' : |
20 | case '[object Boolean]' : |
22 | case '[object Number]' : |
24 | case '[object Function]' : |
26 | case '[object RegExp]' : |
28 | case '[object Object]' : |
29 | if (undefined !== value.nodeType) { |
30 | if (3 == value.nodeType) { |
31 | return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace' ; |