我试图扩展JS Number原型以包含一个Ruby-esque" .times"方法(这种追求的优点是另一个问题)。
这是我的代码:
Number.prototype.times = function(doThis) {
val = +this;
while (val > 0 ) {
doThis();
val--;
}
}
如果我尝试
5..times(console.log(1));
我得到以下输出:
foo
TypeError: undefined is not a function (evaluating 'doThis()')
为什么循环在第一次迭代时起作用而在第二次迭代时失败?
(注意:目标是使Number原型扩展,使其调用它具有高度表现力,直观性,并且更像自然语言,如Ruby的.times方法。)
答案 0 :(得分:4)
您的Number.prototype.times
函数会写入将另一个函数作为参数(您之后使用doThis()
进行调用)。
但是,在调用times
函数时,您并未将另一个函数作为参数传递,而是返回console.log(1)
的值,该值很可能是undefined
(其中您之后尝试作为函数调用,导致 undefined不是函数错误。)
相反,传递一个调用console.log(1)
:
5..times(function() {
console.log(1);
});
答案 1 :(得分:0)
您的功能让我想起了underscore或lodash这样的库,这些库提供了许多功能,可以让您制作非常简洁的代码。
以下是我可以使用lodash实现这一点的方法,它提供了_.times()实用程序函数:
Number.prototype.times = function(cb) {
return _.times(+this, cb);
}
您可以使用_.partial()使其比明确的function() {}
包装更具可读性:
5..times(_.partial(console.log,"blah"));
或者,如果您想将部分放入times
函数中,它可能会更具可读性:
Number.prototype.times = function () {
return _.times(+this, _.partial.apply(this,arguments));
};
5..times(console.log,"blah");
// can still be used with an arbitrary function block:
5..times(function() { console.log("some other block"); });
答案 2 :(得分:-1)
改为:
Number.prototype.times = function(doThis) {
val = +this;
while (val > 0 ) {
doThis();
val--;
}
}
5..times(function () {console.log(1)});