gpt4 book ai didi

javascript 添加函数脚本 - 有人能解释一下吗?

转载 作者:行者123 更新时间:2023-12-03 07:47:54 26 4
gpt4 key购买 nike

我在一个示例中寻找这段代码,它应该按名称在对象上创建函数。据我了解,它还可以在对象上创建相同函数的重载。

function addMethod(object, name, fn) {
var old = object[name];
object[name] = function(){
if (fn.length == arguments.length)
return fn.apply(this, arguments)
else if (typeof old == 'function')
return old.apply(this, arguments);
};
}

所以如果创建一个新对象,例如

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 */ });

该对象应包含 3 个任意函数的重载。

我不明白addMethod函数的问题:

我知道我们将最后一个函数存储在old中。我们用这种方式创建一个闭包吗?使用匿名函数?

因此执行这行代码:

 else if (typeof old == 'function')
return old.apply(this, arguments);

它会递归调用之前定义的所有函数直到匹配?

谁能解释一下吗?

谢谢

最佳答案

but don't understand what we store with the new anonymous function

代码的要点是根据传递的参数数量调用不同版本的函数。

如果你不将旧版本的函数存储在某个地方,那么就没有任何方法可以调用它。

why we testing fn.lenth into arguments length (doesn't args.arguments are the 3 always? of (addMethod))

函数的length属性是预期参数的数量。即创建它的函数声明或函数表达式的 () 之间的标识符数量。

arguments 对象的 length 属性是实际传递给它的参数数量。

请参阅此示例:

function myFunction(foo, bar) {
document.body.appendChild(
document.createElement("br")
);
document.body.appendChild(
document.createTextNode(
"The function was called with " + arguments.length + " arguments"
)
);
}


document.body.appendChild(
document.createTextNode(
"The length of the function is " + myFunction.length
)
);

myFunction();
myFunction("a", "b", "c", "d", "e");

关于javascript 添加函数脚本 - 有人能解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com