我正在尝试扩展 JS Number 原型(prototype)以包含 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 原型(prototype)扩展,使其调用具有高度表现力、直观性,并且读起来更像自然语言,如 Ruby 的 .times 方法。)
最佳答案
您的 Number.prototype.times
函数被编写为将另一个函数作为参数(然后您使用 doThis()
调用该函数) )。
但是,在调用 times
函数时,您不会传递另一个函数作为参数,而是返回 console.log(1)
的值,这将最可能是未定义
(然后您尝试将其作为函数调用,导致未定义不是函数错误)。
相反,传递一个调用 console.log(1)
的函数:
5..times(function() {
console.log(1);
});
关于javascript - Number 原型(prototype)扩展中的 while 循环调用函数一次,然后出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235403/