在《javascript忍者秘籍》上看到一段代码,用于函数重载。function addMethod(object, name, fn) { var old = object[name]; //#1
object[name] = function(){ if (fn.length == arguments.length) //#2
return fn.apply(this, arguments) //#2
else if (typeof old == 'function') //#3
return old.apply(this, arguments); //#3
};
}示例是这样的:var ninja = {};
addMethod(ninja,'whatever',function(){/*do something*/});
addMethod(ninja,'whatever',function(a){/*do something else*/});
addMethod(ninja,'whatever',function(a,b){/*yet something else*/});但是有点看不懂addMethod方法,疑问如下:if (fn.length == arguments.length)这个arguments是谁的arugments?调用addMethod时的?还是object[name] = function()这个匿名函数?菜鸟一枚,若拍砖请轻拍
1 回答
狐的传说
TA贡献1804条经验 获得超3个赞
你只需要加两句话做个试验就清楚了
function addMethod(object, name, fn) { var _addMethodArguments = arguments; var old = object[name]; //#1 object[name] = function() { console.log("is arguments of addMethod():", _addMethodArguments === arguments); if (fn.length == arguments.length) //#2 return fn.apply(this, arguments); //#2 else if (typeof old == "function") //#3 return old.apply(this, arguments); //#3 }; }var ninja = {}; addMethod(ninja, "whatever", function() {/*do something*/ }); ninja.whatever();
添加回答
举报
0/150
提交
取消