javascript - while loop in Number prototype extension calls function once, then errors undefined -


i'm trying extend js number prototype include ruby-esque ".times" method (the merits of pursuit issue time).

here code:

number.prototype.times = function(dothis) {   val = +this;   while (val > 0 ) {     dothis();     val--;   } } 

if try

5..times(console.log(1));

i following output:

foo typeerror: undefined not function (evaluating 'dothis()') 

why loop work on first iteration , fail on second?

(note: goal make number prototype extension such calling highly expressive, intuitive, , reads more natural language, ruby's .times method.)

your number.prototype.times function written take function argument (which you're calling dothis()).

however, when calling times function, you're not passing function parameter, return value of console.log(1) undefined (which you're trying call function, resulting in undefined not function error).

instead, pass function that's calling console.log(1):

5..times(function() {     console.log(1); }); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -