jquery和widget源码分析(一)

Jquery框架结构如图:

所有通过$();返回的jquery对象都是jQuery.fn.init实例对象,而jQuery.fn.init.prototype被指定为jQuery.fn,这样所有挂在jQuery.fn上的方法都是jQuery实例方法。
jQuery.fn=jQuery.prototype;从而所有jQuery实例的原型对象==jQuery.prototype,所以所有$(xxx) instanceof jQuery结果是true。
jQuery实例是什么?

比如最常用的$(“#myId”),返回的结果就是一个init实例,它就是一个js对象,这个对象缓存了id为myId的元素、document等。同时这个对象拥有jQuery.fn里面定义的所有方法。
jQuery最常用的方法之一:extendjQuery.extend = jQuery.fn.extend =function() {
varoptions, name, src, copy, copyIsArray, clone,
//第0个参数为目标扩展对象
target= arguments[0] || {},
i= 1,//第一个参数为起始待扩展对象
length= arguments.length,
deep= false;
//Handle a deep copy situation
//如果第0个参数是布尔类型,则把第一个参数作为目标扩展对象,起始待扩展对象向后推一位
if( typeof target === "boolean" ) {
deep= target;
target= arguments[1] || {};
//skip the boolean and the target
i= 2;
}
//Handle case when target is a string or something (possible in deep copy)
if( typeof target !== "object" && !jQuery.isFunction(target) ){
target= {};
}
//extend jQuery itself if only one argument is passed
//除是否深拷贝,只传了一个对象,则被扩展对象设置为this
if( length === i ) {
target= this;
--i;
}
//除被扩展对象外,把剩余的所有对象作为扩展对象,顺序扩展到目标对象中
for( ; i < length; i++ ) {
//Only deal with non-null/undefined values
if( (options = arguments[ i ]) != null ) {
//Extend the base object
for( name in options ) {
src= target[ name ];
copy= options[ name ];
//Prevent never-ending loop
if( target === copy ) {
continue;
}
//Recurse if we're merging plain objects or arrays
if( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray= jQuery.isArray(copy)) ) ) {
if( copyIsArray ) {
copyIsArray= false;
clone= src && jQuery.isArray(src) ? src : [];
}else {
clone= src && jQuery.isPlainObject(src) ? src : {};
}
//Never move original objects, clone them
//深拷贝
target[name ] = jQuery.extend( deep, clone, copy );
//Don't bring in undefined values
}else if ( copy !== undefined ) {
//非深拷贝直接引用
target[name ] = copy;
}
}
}
}
//Return the modified object
returntarget;
};
此方法参数格式jQuery.extend([deep],object1,[object2,……]);deep为布尔类型,可以不传,如果传true则后面的拷贝为深拷贝,否则直接引用,如果自由一个object,这this默认成为目标扩展对象并返回t
jquery和widget源码分析(一)
声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。如若本站内容侵犯了原著者的合法权益,可联系本站删除。



