天天看點

模仿JQuery.extend函數擴充自己對象的js代碼

如果要在之前寫好的對象中添加新的靜态方法或執行個體方法,要修改原有的對象結構,于是檢視了jquery了extend方法,果然extend方法支援了jq的半邊天,拿來主義,給自己的對象做擴張用。

下面進入正題: 

假如有以下一個對象 

var MyMath = {

//加法

Add: function(a, b){

return a + b;

},

//減法

Sub: function(a, b){

return a - b;

}

}  

對象名MyMath,有兩個靜态方法Add和Sub,正常調用: 

alert(MyMath.Add(3, 5)) //結果8  

好,現在如果現在MyMath增加兩個靜态方法(乘法、除法)怎麼辦,并且不要修改之前寫好的對象,以前我們可以這麼做: 

//新加一靜态方法:Mul乘法

MyMath["Mul"] = function(a, b){

return a * b;

}

//新加一靜态方法:Div除法

MyMath["Div"] = function(a, b){

return a / b;

}  

這樣,我們給MyMath添加兩個方法:Mul和Div。正常調用:

alert(MyMath.Add(3, 5)) //結果8

alert(MyMath.Mul(3, 5)) //結果15  

但是,剛才增加方法的寫法有點笨拙,每增加一個方法都要寫一次對象名(MyMath),能不能想之前我們建立對象的時候那樣,通過Json的結構去聲明一個對象呢? 

答案當然是可以了,通過模拟JQuery.extend函數,輕松做到。以下提取JQuery.extend函數并修改了函數名: 

MyMath.extend = function(){

// copy reference to target object

var target = arguments[0] ||

{}, i = 1, length = arguments.length, deep = false, options;

// Handle a deep copy situation

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

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 (var name in options) {

var src = target[name], copy = options[name];

// Prevent never-ending loop

if (target === copy)

continue;

// Recurse if we're merging object values

if (deep && copy && typeof copy === "object" && !copy.nodeType)

target[name] = jQuery.extend(deep, // Never move original objects, clone them

src || (copy.length != null ? [] : {}), copy);

// Don't bring in undefined values

else

if (copy !== undefined)

target[name] = copy;

}

// Return the modified object

return target;

};  

現在我們通過這個extend方法來增加剛才我們的方法(乘法、除法): 

MyMath.extend({

Mul: function(a, b){

return a * b;

},

Div: function(a, b){

return a / b;

}

});