创建重复方法

时间:2015-03-11 17:29:01

标签: javascript

我已经做了一些方法来轻松地多次重复一个函数(而不是使用循环,因为它们很长而且很累,至少对我而言)。



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

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




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

Uncaught TypeError: Illegal invocation.

关于可能导致这种情况的任何想法?

2 个答案:

答案 0 :(得分:4)

document.write的上下文必须为document,因此您对.repeat的lib调用不会对document.writeconsole.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");

另请参阅:why can't you do [array].forEach(console.log)