gpt4 book ai didi

javascript - 创建重复方法

转载 作者:行者123 更新时间:2023-11-28 15:25:52 25 4
gpt4 key购买 nike

我做了一个小方法来轻松地重复一个函数几次(而不是使用循环,因为它们又长又累,至少对我来说)。

Function.prototype.repeat = function(count,params) {
while(count--) this.apply(this, params);
};

document.write.repeat(4,["Hi"]);

我希望它能很好地执行并正确编写。好吧,在 while 循环行中,出现了错误!!

Uncaught TypeError: Illegal invocation.

有什么想法可能导致这种情况吗?

最佳答案

document.write 的上下文必须是 document,因此您对 .repeat 的 lib 调用将不适用于 等函数>document.writeconsole.log 除非您使用参数来指定上下文,或者已经绑定(bind)了上下文。

Function.prototype.repeat = function(ctx, count, params) {
// ^^^
while(count--) this.apply(ctx, params);
// ^^^
};

document.write.repeat(document, 4, ["Hi"]);
// ^^^^^^^^

或者:

Function.prototype.repeat = function(count, params) {
while(count--) this.apply(this, params);
};
document.write.bind(document).repeat(4, ["Hi"]);
// ^^^^^^^^^^^^^^^

关于javascript - 创建重复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993389/

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