相关源码介绍
var type = jQuery.type(obj) // 源码调用地方
jQuery.type = toType // 实际方法是toType
function toType(obj) {
if (obj == null) {
return obj + "" // 如果是null就输出字符串'null'
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function"
? class2type[toString.call(obj)] || "object" // 这个"object"我感觉有点多余,如果是function就得到function,如果是object就得到object,永远用不上这个"object"
: typeof obj // 返回基础类型
}
var class2type = {} // 默认空对象
var toString = class2type.toString // 定义toString等于空对象上的toString
jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol"
.split(" "), function (_i, name) {
class2type["[object " + name + "]"] = name.toLowerCase()
}
) // 遍历相关类型并转成小写字符串
执行 jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" ") 得到:
console.log(class2type)
{
['object Array']: "array",
['object Boolean']: "boolean",
['object Date']: "date",
['object Error']: "error",
['object Function']: "function",
['object Number']: "number",
['object Object']: "object",
['object RegExp']: "regexp",
['object String']: "string",
['object Symbol']: "symbol"
}
验证相关类型:
Object
const a = {};
jQuery.type(a); // 'object'
Date
const a = new Date();
jQuery.type(a); // 'date'
Function
function a () {};
jQuery.type(a); // 'function'
Number
const a = 1;
jQuery.type(a); // 'number'
总结
至此,jQuery.type()可满足所有类型的判断!
使用原生JS封装一个函数
function typeJudgment (obj) {
const class2type = {
['object Array']: "array",
['object Boolean']: "boolean",
['object Date']: "date",
['object Error']: "error",
['object Function']: "function",
['object Number']: "number",
['object Object']: "object",
['object RegExp']: "regexp",
['object String']: "string",
['object Symbol']: "symbol"
}
if (obj == null) {
return obj + ""
}
return typeof obj === "object" || typeof obj === "function"
? class2type[Object.prototype.toString.call(obj)] || "object"
: typeof obj
}