实现原理
浅拷贝 jQuery.extend(clone, copy)
实现原理:效果查看
key值不同: 以clone、copy合集为准
key值相同: value值为基本类型直接覆盖; 为对象或数组若 则以copy为准;
#### 深拷贝 jQuery.extend(true, clone, copy)
实现原理: 效果查看
key值不同: 以clone、copy合集为准
key值相同: value值为基本类型直接覆盖;
为对象或数组 嵌套形式则取两者合集, 直接对象或数组则直接覆盖;
### jQuery 源码片段
/* 继承实现 依赖 */
// Object对象
var class2type = {};
var toString = class2type.toString;
// 检测是否为对象本身属性而非继承
var hasOwn = class2type.hasOwnProperty;
// 获取对象原型函数
var getProto = Object.getPrototypeOf;
// 对象的实现(函数体)
var fnToString = hasOwn.toString;
// Object实现 "function Object() { [native code] }"
var ObjectFunctionString = fnToString.call( Object );
// 是否为纯对象或数组, 目的:是否需要深度遍历对象
var isPlainObject = function( obj ) {
var proto, Ctor;
// obj 是否为对象
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
// obj 对象原型
proto = getProto( obj );
// 是否有原型对象 Object.create( null )无[prototype]
if ( !proto ) {
return true;
}
//获取对象构造函数,若为Object直接创建则为 function Object()
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
//是否为Object直接对象
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
};
/* 继承实现 */
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
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// 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
if ( i === length ) {
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 = 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 ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};