而Number原型扩展中的循环调用函数一次,然后出现未定义的错误
while loop in Number prototype extension calls function once, then errors undefined
我正在尝试扩展JS Number原型,以包括Ruby风格的".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方法。(
您的Number.prototype.times
函数被编写为将另一个函数作为参数(然后使用doThis()
调用该函数(。
但是,在调用times
函数时,您不是将另一个函数作为参数传递,而是返回console.log(1)
的值,该值很可能是undefined
(然后您试图将其作为函数调用,导致未定义不是函数错误(。
相反,传递一个调用console.log(1)
:的函数
5..times(function() {
console.log(1);
});
您的函数让我想起了像下划线或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"); });
下面是一个jsfiddle示例。
更改为:
Number.prototype.times = function(doThis) {
val = +this;
while (val > 0 ) {
doThis();
val--;
}
}
5..times(function () {console.log(1)});
相关文章:
- 有没有一个抽象层,这样我就可以集成一次,然后使用pusher、pubnub或faye
- 如果30秒未单击,请应用CSS一次,将其删除,然后重新迭代
- 设置随机数,然后每5秒随机减少一次,直到达到0(javascript)
- 显示数字,然后每5秒随机更改一次(javascript)
- 单击时预置图像 - 仅预置一次,然后停止
- 如何每 10 秒调用一次 JS 函数,然后以角度激活一个函数
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- 做一件事,然后在react js中每隔15秒做一次
- 地图,rails 4.2,javascript,鼠标悬停,只工作一次(或两次).然后在重新加载之后
- 一次选中4个复选框,然后将页面重定向到新页面
- 其中是在ReactJS中放置一个值的最佳位置,该值由传入的初始参数计算一次,然后再也不会更改
- Flickity gallery - 如何循环浏览一次然后停止自动播放
- 引导 2 轮播循环一次,然后停止
- 如何使函数在 2 分钟后执行,然后每隔 2 分钟执行一次
- Javascript 这个关键字在原型函数中的递归执行一次,然后未定义
- 调用函数一次,然后设置间隔
- 然后,Jquery 加载内容每 2 秒刷新一次
- jQuery事件触发一次,然后再也不会触发
- 如何只运行一个函数一次,然后运行另一个依赖于相同元素的函数
- 加载带有引导模式的ajax页面,然后一次自动启动该模式