Home >Web Front-end >JS Tutorial >Simulation code of jQuery's implementation principle -4 important extension functions extend_jquery

Simulation code of jQuery's implementation principle -4 important extension functions extend_jquery

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 18:21:511141browse

jQuery.fn.extend provides an extension mechanism that allows us to extend an object through one or more sample objects. If the object to be extended is not specified, it will be extended to itself.

jQuery.extend can also be used through jQuery.fn.extend, which is used a lot in jQuery to extend members of a target object. The extended members come from a series of reference objects.
This way, if we need to removeData for the jQuery.fn extension member, we can do it like this.

Copy code The 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, it has not been simplified too much.
Copy code The code is as follows:

///
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 case of deep copy, the first parameter is The boolean type, then, represents a 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 not an object or a function
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// If there is only one parameter, expand itself
if (length === i) {
target = this;
--i;
}
// Traverse all reference objects and expand 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;
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn