在JQuery中有一个type方法,在1.11.2中是这样写的
var class2type = {};
var toString = class2type.toString;
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
}
其核心在于使用Array.prototype.toString.call,因为在任何值上调用Object原生的toString()方法,都会返回一个[object NativeConstructorName]格式的字符串。每个类在内部都有一个[[Class]]属性,这个属性中就指定了上述字符串中的构造函数名。
之所以这样做是因为js内置的类型检测机制并非完全的可靠。
例如,typeof null 输出“object”
typeof alert 在IE8中输出“object”
typeof [] 输出“object”网址:yii666.com
instanceof如果是跨文档比较的话,就会存在很大的问题。利用constructor属性的话,在低版本IE中又会出现问题(window.constructor在IE7下为undefined)。而且,二者不方便判断基本类型。
所以说,判断是否是函数,数组就可以这样写
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
}, isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
奇怪的是判断是否为window
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
似乎伪装一下也能骗过去,可能是因为window对象属于BOM,前面的方法对它不管用。文章来源地址:https://www.yii666.com/article/756278.html
然后是isPlainObject,2.0.1中这样写。
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
} // Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
} // If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
}
这里的PlainObject应该是如{},new Object,这样的对象。
第一个if可以排除非Object对象,dom节点,window。
第二个if是可以排除window.location这样的BOM对象。
其中,
class2type = {},
core_hasOwn = class2type.hasOwnProperty
因为这些BOM对象的构造函数的原型肯定不是Object {},自身是没有isPrototypeOf这个属性的。
然后是判断空对象,也就是没有可枚举属性的对象。文章地址https://www.yii666.com/article/756278.html
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
}
还有一个函数是用来判断是否是数字,
//1.11.2
isNumeric: function( obj ) {
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
向parseFloat中传个数组,如[2,4],返回2,但是数组参加右边的运算结果肯定是false,不知道为什么要先判断是否是数组。
这里如果传入一个如'123'、'321'这样的字符串的话也是可以通过的。
在1.8.0和2.0.1版本中直接就是!isNaN( parseFloat(obj) ) && isFinite( obj ).