解析Object.prototype.toString.call()进行数据类型判断
首先看一段ECMA中对Object.prototype.toString的解释:
1.If the this value is undefined, return "[object Undefined]".
2.If the this value is null, return "[object Null]".
3.Let O be the result of calling ToObject passing the this value as the argument.
4.Let class be the value of the [[Class]] internal property of O.
5.Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
翻译:
1.如果this的值为undefined,则返回"[object Undefined]".
2.如果this的值为null,则返回"[object Null]".
3.让O成为调用ToObject(this)的结果.
4.让class成为O的内部属性[[Class]]的值.
5.返回三个字符串"[object ", class, 以及 "]"连接后的新字符串.
查看Jquery就会发现,jquery就是是通过Object.prototype.toString.call还判断对象的类型的,那究竟如何做呢?
我们先来了解一下call方法:
function a(){
this.aa=function(){
alert("a");
}
}
function b(){
alert(a.call(this));
}
var c=new b();
c.aa();
call方法可以让b复制a里面的方法来进行使用,也就是所谓的继承。
var obj = {name:"Tom", age:18};
console.log(typeof obj.toString()); //string
console.log(obj.toString()); //"[object Object]"
我们知道,Javascript中,一切皆为对象。所以如下代码,应当会输出对应字符:
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]
标准浏览器中完美的作到,但是(为什么要说但是呢)IE6中,却会出现以下问题:
通过Object.prototype.toString.call获取的 字符串,undefined,null均为Object
所以,我们又要悲剧的先对以上类型进行判断,完整代码:
var oP = Object.prototype,
toString = oP.toString;function typeOf(value) {
if (null === value) {
return 'null';
}var type = typeof value;
if ('undefined' === type || 'string' === type) {
return type;
}var typeString = toString.call(value);
switch (typeString) {
case '[object Array]':
return 'array';
case '[object Date]':
return 'date';
case '[object Boolean]':
return 'boolean';
case '[object Number]':
return 'number';
case '[object Function]':
return 'function';
case '[object RegExp]':
return 'regexp';
case '[object Object]':
if (undefined !== value.nodeType) {
if (3 == value.nodeType) {
return (/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';
} else {
return 'element';
}
} else {
return 'object';
}
default:
return 'unknow';
}
}
参考文档:
1. https://segmentfault.com/n/1330000004202636
2. http://openxtiger.iteye.com/blog/1893378
3. http://my.oschina.net/sfm/blog/33197