用过Jquery的朋友都知道,Jquery是通过Object.prototype.toString.call还判断对象的类型的,那究竟如何做呢?
来到http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2的一段话:
Object.prototype.toString ( )
When the toString method is called, the following steps are taken:
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, 以及 "]"连接后的新字符串.
因此通过调用后Object.prototype.toString.call(),都会返回 [object class]的样式,我们可以先记录起这些样式,反过来判断。
var class2type = {}, //用于记录[object class]样式 objs = "Boolean Number String Function Array Date RegExp Null Undefined".split(" "); for (var i = 0, l = objs.length; i < l; i++) { class2type[ "[object " + objs[i] + "]" ] = objs[i].toLowerCase(); } function type(obj) { return class2type[ Object.prototype.toString.call(obj) ] || "object"; }