jQuery中extend的使用方式大多是这样的:
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
// Assume jQuery is ready without the ready module
isReady: true,
error: function (msg) {
throw new Error(msg);
},
})
jQuery几乎在每一部分模块代码的下方,都会加上这样的一段代码,来添加操作该模块的属性和方法。
如果去搜索jQuery.extend会发现,这个函数还可以这么用:
var udataCur = jQuery.extend({
}, udataOld);
var anim = Animation(this, jQuery.extend({
}, prop), optall);
这样的使用方法,可不太像是添加扩展了。一个函数不只能实现一个功能?不如去看看,函数内部是怎么实现的,以及这个函数到底能用来干什么。
.extend源码:
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" && !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]) !=