欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery的實(shí)現(xiàn)原理的模擬代碼 -4 重要的擴(kuò)展函數(shù) extend

 更新時(shí)間:2010年08月03日 00:34:10   作者:  
在上兩篇文章中,我們看到每次要通過(guò) jQuery 的原型增加共享方法的時(shí)候,都需要通過(guò) jQuery.fn 一個(gè)個(gè)進(jìn)行擴(kuò)展,非常麻煩.
jQuery.fn.extend 提供了一個(gè)擴(kuò)展機(jī)制,可以方便我們通過(guò)一個(gè)或者多個(gè)示例對(duì)象來(lái)擴(kuò)展某個(gè)對(duì)象。如果沒(méi)有指定被擴(kuò)展的對(duì)象,那么將擴(kuò)展到自己身上。

jQuery.extend 也可以通過(guò) jQuery.fn.extend 使用, 在 jQuery 中使用很多,用來(lái)為一個(gè)目標(biāo)對(duì)象擴(kuò)展成員,擴(kuò)展的成員來(lái)自于一系列參考對(duì)象。
這樣,如果我們需要為 jQuery.fn 擴(kuò)展成員 removeData,就可以這樣進(jìn)行。
復(fù)制代碼 代碼如下:

jQuery.fn.extend(
{
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
}
);

extend 的源碼如下,因?yàn)楸容^簡(jiǎn)單,所以沒(méi)有做太多的精簡(jiǎn)。
復(fù)制代碼 代碼如下:

/// <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 // 深拷貝情況,第一個(gè)參數(shù)為 boolean 類型,那么,表示深拷貝,第二個(gè)參數(shù)為目標(biāo)對(duì)象
9 if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// 如果目標(biāo)不是對(duì)象也不是函數(shù)
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// 如果只有一個(gè)參數(shù)就是擴(kuò)展自己
if (length === i) {
target = this;
--i;
}
// 遍歷所有的參考對(duì)象,擴(kuò)展到目標(biāo)對(duì)象上
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;
};

相關(guān)文章

最新評(píng)論