Skip to content

常见函数封装 ​

本节目标:理解“常见函数封装”的核心思路,并能把它用于实际开发或面试表达。 检测变量类型

function typeOf(arg) {
return typeof arg !== 'object' ? typeof arg : Object.prototype.toString.call(arg);
}
console.log(typeOf([1,2]));
function typeOf(arg) {
if (typeof arg !== 'object') {
return typeof arg;
}
return Object.prototype.toString.call(arg);
}
console.log(typeOf([1,2]));

jquery3.3.1中的方法

"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call(Object);
var support = {};
var isFunction = function isFunction(obj) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
var isWindow = function isWindow(obj) {
return obj != null && obj === obj.window;
};
var preservedScriptAttributes = {//

保藏的

type: true,
src: true,
noModule: true
};
function DOMEval(code, doc, node) {
doc = doc || document;
var i,
script = doc.createElement("script");
script.text = code;
if (node) {
for (i in preservedScriptAttributes) {
if (node[i]) {
script[i] = node[i];
}
}
}
doc.head.appendChild(script).parentNode.removeChild(script);
}
function toType(obj) {
if (obj == null) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
//

运算符优先级 // typeof 与 ! 同级 // 比较运算符(== ===) \> 逻辑运算符

(! > && > ||)
//

最后三元运算符

return typeof obj === "object" || typeof obj === "function" ?
class2type[toString.call(obj)] || "object" :
typeof obj;
}