jQuery源码分析6: jQuery.isEmptyObject与jQuery.isPlainObject
var hasOwn = Object.prototype.hasOwnProperty,
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
// 必须是一个Object,同时需要过滤掉DOM对象
// Because of IE, we also have to check the presence of the constructor property.
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// 拥有自己的constructor属性必然不是Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
测试:
jQuery.isPlainObject({}); // true
var hasOwn = Object.prototype.hasOwnProperty,
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
// 必须是一个Object,同时需要过滤掉DOM对象
// Because of IE, we also have to check the presence of the constructor property.
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// 拥有自己的constructor属性必然不是Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
测试:
jQuery.isPlainObject({}); // true
本文详细解析了jQuery中用于检测对象是否为空的isEmptyObject方法及判断是否为纯对象的isPlainObject方法。通过源码分析,揭示了这两种方法的具体实现方式,并通过示例验证其正确性。
797

被折叠的 条评论
为什么被折叠?



