本文实例讲述了JQuery中extend的用法。分享给大家供大家参考。具体分析如下:
extend()函数是jQuery的基础函数之一,作用是扩展现有的对象。extend是我们在写插件的过程中常用的方法,该方法有一些重载原型。$.extend(prop) 用于扩展jQuery对象,可以用于把函数添加到jQuery名称空间中。
一、jQuery.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
//如果为深度复制,则目标对象和原对象游标值i,以及深度值都进行更新
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
//当参数值长度为1的情况下,目标对象就为jQuery自身
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
//深度复制只有属性深度多于俩层的对象关系的结构的,如{a:{s:21,age:11}}或{a:['s'=>21,'age'=>11]}
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 ) {//非深度CP直接覆盖目标属性
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;










