您的位置:首页 > Web前端 > JQuery

jQuery中extend()源码分析

2017-08-24 15:11 453 查看
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;

// Handle a deep copy situation
//判断是否是深拷贝,如$.extend(true,object1,boject2)
//deep变为true,target变为object1
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)
//用来处理不正确的参数,target必须是object或者函数类型,如果不是,赋值一个空的{}
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}

// extend jQuery itself if only one argument is passed
//当只有一个参数时,用来扩展方法,如插件的使用
if ( length === i ) {
target = this;//当jQuery.extend()时,this指jQuery,添加工具方法;jQuery.fn.extend(),this指jQuery.fn,添加实例方法
--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
//因为var a = {};
// a.name=a;这种情况会无限循环,a.name.name.name.name...要避免这种情况
if ( target === copy ) {
continue;
}

// Recurse if we're merging plain objects or arrays
//当deep为真,copy存在并且copy时对象自变量({},new Object)或array,执行
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
如果copy时数组
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];//src存在并且是数组,src不变,否则赋值空数组

} else {
//src存在并且是对象自变量,src值不变,否则赋值{}
clone = src && jQuery.isPlainObject(src) ? src : {};
}

// Never move original objects, clone them
/*举例说明:
*
*var a = { name : { job : 'it' } };
var b = { name : {age : 30} };
由于copy=b[name]是{age:30},对象自变量,就要再次调用extend(true,a[name],b[name])
b[name].age是number不是对象自变量,直接执行target[ name ] = copy;
a[name]就是{job : 'it',age : 30}
*/

target[ name ] = jQuery.extend( deep, clone, copy );

// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}

// Return the modified object
return target;
};


举例:

深拷贝:

var a = { name : { firstName : 'Tom' } };
var b = { name : {firstName : 'Jack',lastName:'Simith'} };
$.extend( true , a , b );
alert(a.name.firstName);//Jack
alert(a.name.lastName);//Simith
alert(b.name.firstName);//Jack
alert(b.name.lastName);//Simith
//对a中的firstName进行修改,不会影响b中的firstName
a.name.firstName= 'William';
alert(a.name.first
4000
Name);//William
alert(b.name.firstName);//Jack

浅拷贝:

var a = { name : { firstName : 'Tom' } };
var b = { name : {firstName : 'Jack',lastName:'Simith'} };
$.extend( a , b );
alert(a.name.firstName);//Jack
alert(a.name.lastName);//Simith
alert(b.name.firstName);//Jack
alert(b.name.lastName);//Simith
//对a中的firstName进行修改,b中的firstName也会发生变化
a.name.firstName= 'William';
alert(a.name.firstName);//William
alert(b.name.firstName);//William
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: