jQuery 中一个重要的函数便是 extend,可以用它进行浅拷贝和深拷贝。
用它来对本身 jQuery 的属性和方法进行扩张,又可以对原型的属性和方法进行扩展。
jQuery.extend(target);// jQuery 的扩展
jQuery.extend(target, obj1, obj2,..);//浅拷贝
jQuery.extend(false, target, obj1, obj2,..);//浅拷贝
jQuery.extend(true, target, obj1, obj2,..);//深拷贝
下面是jQuery.3.3.1.js 中的源码
jQuery.extend = jQuery.fn.extend = function() {//fn指的是prototype
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
//如果第一个值为null,那么target已经为{};他是一个对象
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {//判断是否是布尔值,方便判断是浅拷贝或者深拷贝
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};//target是第二个参数;
i++;
}
// 处理 target 是字符串或奇怪的情况,isFunction(target) 可以判断 target 是否为函数
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed,判断是否 jQuery 的扩展
if ( i === length ) {
// this 做一个标记,可以指向 jQuery,也可以指向 jQuery.fn
target = this;
i--;//0
}
for ( ; i < length; i++ ) {
// null/undefined 判断
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;
}
// 是数组或者对象(非函数,可以是null,)进入循环
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.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 ) {
//这一句。不能拷贝undefined,可以拷贝undefined
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
这个方法可以拷贝null,函数,数组,但是拷贝不了undefined。