jQuery源码阅读:类型判断 type 方法
let class2type = {}
core_toString = class2type.toString
core_hasOwn = class2type.hasOwnProperty
// Populate the class2type map : 填充class2type
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// 最后结果应该是这种形式: {'[object string]': 'string', '[Object Array]': 'array'}
作用:在使用 toString
方法判断变量类型的时候会很方便
用在了type方法中
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
}
- 如果obj不是引用类型,直接返回
typeof obj
- 如果 obj 是引用类型
- 如果调用toString方法之后可以在
class2type
中找到,那就返回对应类型 - 如果在
class2type
中找不到,那么就直接返回 “object”
- 如果调用toString方法之后可以在