2
在John Resig tutorial on Javascript超載,還有用於函數重載,一個代碼,我無法弄清楚它是如何工作:功能的Javascript
function addMethod(object, name, fn){
// Save a reference to the old method
var old = object[ name ];
// Overwrite the method with our new one
object[ name ] = function(){
// Check the number of incoming arguments,
// compared to our overloaded function
if (fn.length == arguments.length)
// If there was a match, run the function
return fn.apply(this, arguments);
// Otherwise, fallback to the old method
else if (typeof old === "function")
return old.apply(this, arguments);
};
}
function Ninjas(){
var ninjas = [ "Dean Edwards", "Sam Stephenson", "Alex Russell" ];
addMethod(this, "find", function(){
return ninjas;
});
addMethod(this, "find", function(name){
var ret = [];
for (var i = 0; i < ninjas.length; i++)
if (ninjas[i].indexOf(name) == 0)
ret.push(ninjas[i]);
return ret;
});
addMethod(this, "find", function(first, last){
var ret = [];
for (var i = 0; i < ninjas.length; i++)
if (ninjas[i] == (first + " " + last))
ret.push(ninjas[i]);
return ret;
});
}
- 爲什麼第二
addMethod
不隨寫第一個? - 爲什麼我們需要保留對
old
的參考?
但之後的第三'addMethod'被調用時,我們有'this.find'指向一個功能,在它的內部,'fn'預計2個參數參數和舊參數在參數中期望1個參數。沒有理由的情況下會發生什麼。這是如何處理的? –
@ArianHosseinzadeh讓我編輯而不是回答。 –