先看看zepto中的$.extend用法
API中是这样说
.extend(true, target, [source, ...]) ⇒ target v1.0+
通过源对象扩展目标对象的属性,源对象属性将覆盖目标对象属性。
默认情况下为,复制为浅拷贝(浅复制)。如果第一个参数为true表示深度拷贝(深度复制)。
var a={one:"dd"};
var c={ two: 'turtle doves' }
var b= $.extend(a,c)
b.one="aa"
a
Object {one: "aa", two: "turtle doves"}
将第二个以后的对象合并到第一个对象,并返回第一个对象,如果键名有重复,后面的覆盖前面的 再来看看它怎么实现的
function extend(target, source, deep) {
for (key in source)
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
// Copy all but undefined properties from one or more
// objects to the `target` object.
$.extend = function(target){
//slice在这里取出数组中除了第一个
var deep, args = slice.call(arguments, 1)
if (typeof target == 'boolean') {
deep = target
//shift删除第一个元素,并返回第一个,也就是去第一个元素
target = args.shift()
}
args.forEach(function(arg){ extend(target, arg, deep) })
return target
}
再来看看jquery中.extend( {},object1, object2 );` 实现方式也类似
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;
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
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
return target;
};