源码中有这样一段:数组
class2type = {},
toString = class2type.toString,
function type(obj) {
//obj为null或者undefined时,直接返回'null'或'undefined'
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object"
}
// Populate the class2type map
//填充class2type的值
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
--------------------------------------------------------------------------------------------------------缓存
在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、对象来讲,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。函数
要想区别对象、数组单纯使用 typeof 是不行的。或者你会想到 instanceof 方法,例以下面这样:this
-
-
-
-
-
-
console.log(a instanceof Object) //true
-
console.log(b instanceof Object) //true
-
console.log(c instanceof Object) //true
-
-
//只有 Array 类型的 b 才是 Array 的实例
-
console.log(a instanceof Array) //false
-
console.log(b instanceof Array) //true
-
console.log(c instanceof Array) //false
-
-
//只有 Function 类型的 c 才是 Function 的实例
-
console.log(a instanceof Function) //false
-
console.log(b instanceof Function) //false
-
console.log(c instanceof Function) //true
从以上代码来看,要判断复合数据类型,能够以下判断:spa
-
-
(a
instanceof Object) && !(a instanceof Function) && !(a instanceof Function)
-
-
(a
instanceof Object) && (a instanceof Array)
-
-
(a
instanceof Object) && (a instanceof Function)
更简便的方式,便是使用 Object.prototype.toString.call() 来肯定类型,ECMA 5.1 中关于该方法的描述[1]是这样的:prototype
-
When the toString method is called, the following steps are taken:
-
If the this value is undefined, return “[object Undefined]”.
-
If the this value is null, return “[object Null]”.
-
Let O be the result of calling ToObject passing the this value as the argument.
-
Let class be the value of the [[Class]] internal property of O.
-
Return the String value that is the result of concatenating the three Strings “[object “, class, and “]”.
因为 JavaScript 中一切都是对象,任何都不例外,对全部值类型应用 Object.prototype.toString.call() 方法结果以下:code
-
console.log(Object.prototype.toString.call(123)) //[object Number]
-
console.log(Object.prototype.toString.call('123')) //[object String]
-
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
-
console.log(Object.prototype.toString.call(true)) //[object Boolean]
-
console.log(Object.prototype.toString.call({})) //[object Object]
-
console.log(Object.prototype.toString.call([])) //[object Array]
-
console.log(Object.prototype.toString.call(function(){})) //[object Function]
全部类型都会获得不一样的字符串,几乎完美。对象
思考:使用return obj == null ? String(obj) : class2type[obj.toString()] || "object" 也是能够的,做者是先将Object的tostring赋值给toString,three
用意应该是缓存变量, 便于压缩代码,
同时可减小在原型链中的查找次数(提升代码效率)