jQuery源码分析-03构造jQuery对象-工具函数

2020-05-19 07:26:09易采站长站整理

// 检查obj是否是一个纯粹的对象(通过”{}” 或 “new Object”创建的对象)
// console.info( $.isPlainObject( {} ) ); // true
// console.info( $.isPlainObject( ” ) ); // false
// console.info( $.isPlainObject( document.location ) ); // true
// console.info( $.isPlainObject( document ) ); // false
// console.info( $.isPlainObject( new Date() ) ); // false
// console.info( $.isPlainObject( ) ); // false
// isPlainObject分析与重构 //www.jb51.net/article/25047.htm
// 对jQuery.isPlainObject()的理解 http://www.cnblogs.com/phpmix/articles/1733599.html
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don’t pass through, as well
// 必须是一个对象
// 因为在IE8中会抛出非法指针异常,必须检查constructor属性
// DOM节点和window对象,返回false
// obj不存在 或 非object类型 或 DOM节点 或 widnow对象,直接返回false
// 测试以下三中可能的情况:
// jQuery.type(obj) !== “object” 类型不是object,忽略
// obj.nodeType 认为DOM节点不是纯对象
// jQuery.isWindow( obj ) 认为window不是纯对象
if ( !obj || jQuery.type(obj) !== “object” || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
// 测试constructor属性
// 具有构造函数constructor,却不是自身的属性(即通过prototype继承的),
if ( obj.constructor &&
!hasOwn.call(obj, “constructor”) &&
!hasOwn.call(obj.constructor.prototype, “isPrototypeOf”) ) {
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 ) {}
// key === undefined及不存在任何属性,认为是简单的纯对象
// hasOwn.call( obj, key ) 属性key不为空,且属性key的对象自身的(即不是通过prototype继承的)
return key === undefined || hasOwn.call( obj, key );
},
// 是否空对象
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
// 抛出一个异常
error: function( msg ) {
throw msg;
},
// 解析JSON
// parseJSON把一个字符串变成JSON对象。
// 我们一般使用的是eval。parseJSON封装了这个操作,但是eval被当作了最后手段。
// 因为最新JavaScript标准中加入了JSON序列化和反序列化的API。
// 如果浏览器支持这个标准,则这两个API是在JS引擎中用Native Code实现的,效率肯定比eval高很多。
// 目前来看,Chrome和Firefox4都支持这个API。
parseJSON: function( data ) {
if ( typeof data !== “string” || !data ) {
return null;
}