我已经做了一些方法来轻松地多次重复一个函数(而不是使用循环,因为它们很长而且很累,至少对我而言)。
Function.prototype.repeat = function(count,params) {
while(count--) this.apply(this, params);
};
document.write.repeat(4,["Hi"]);

我希望它能很好地执行并正确编写。好吧,在while
循环的行中,出现了错误!!
Uncaught TypeError: Illegal invocation.
关于可能导致这种情况的任何想法?
答案 0 :(得分:4)
document.write
的上下文必须为document
,因此您对.repeat
的lib调用不会对document.write
或console.log
等函数起作用,除非您考虑了一个参数来指定上下文,或者已经绑定了一个上下文。
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"]);
// ^^^^^^^^^^^^^^^

答案 1 :(得分:0)
许多函数依赖于在特定对象的上下文中调用才能正常工作,document.write
是其中一个函数。例如,这会失败,因为函数中的任何this
引用都将使用错误的this
而不是document
:
var w = document.write;
w("hello");
如果您在document
的上下文中正确调用它,它将起作用:
Function.prototype.repeat = function(count) {
while(count--) this.apply(this, Array.prototype.slice.call(arguments, 1));
};
document.write.bind(document).repeat(4, "Hi");