JQuery. fn. extend provides an extension mechanism to extend an object through one or more sample objects. If no extended object is specified, it will be extended to itself.
JQuery. extend can also be used through jQuery. fn. extend. It is widely used in jQuery to expand a member of a target object. Extension members come from a series of reference objects.
In this way, if we need to extend the removeData member for jQuery. fn, we can do this.
Copy codeThe Code is as follows:
JQuery. fn. extend (
{
RemoveData: function (key ){
Return this. each (function (){
JQuery. removeData (this, key );
});
}
}
);
The source code of extend is as follows, because it is relatively simple, so there is not much streamlining.
Copy codeThe Code is as follows:
// <Reference path = "jQuery-core.js"/>
2
3
4 jQuery. extend = jQuery. fn. extend = function (){
5 // copy reference to target object
6 var target = arguments [0] | |{}, I = 1, length = arguments. length, deep = false, options, name, src, copy;
7
8 // In the case of deep copy, the first parameter is of the boolean type, which indicates deep copy, and the second parameter is the target object.
9 if (typeof target = "boolean "){
Deep = target;
Target = arguments [1] || {};
// Skip the boolean and the target
I = 2;
}
// If the target is neither an object nor a function
If (typeof target! = "Object "&&! JQuery. isFunction (target )){
Target = {};
}
// If there is only one parameter, It is the extension of itself.
If (length = I ){
Target = this;
-- I;
}
// Traverse all reference objects and extend them to the target object
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 object literal values or arrays
If (deep & copy & (jQuery. isPlainObject (copy) | jQuery. isArray (copy ))){
Var clone = src & (jQuery. isPlainObject (src) | jQuery. isArray (src ))? Src
: JQuery. isArray (copy )? []: {};
// 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;
};