Hacker News new | past | comments | ask | show | jobs | submit login

It's a good question, and a pretty fair one for a Javascript developer to know, given the role that closures play in the language.

That said, I'm not thinking of a 3rd solution. Closures(best?), a global(worse), what else?

Edit: As Daiz points out, the bind I was thinking of doesn't even have to even be to a global. But we still have seen only two solutions: variations of binding and closures. What's the third? Inquiring minds want to know!




The 3 solutions that I came up with are:

  - bind
  - function creator outside of the loop called from within
  - create an anon function on each loop iteration that acts like the function creator in #2
The bind is best in terms of memory and simplicity, but will not run on on IE 8 or crappier, so in that case #2 is preferred.

The last one creates anon functions needlessly, but is very compact to write.


5 solution with eval

  function foo(s) {
    a = Array(s);
    for (var i = 0; i < s; i++) {
      a[i] = eval('(function () { return ' + i + '})');
    }
    return a;
  }


fourth solution would be naming the function with the iterator (as in my example below) and calling indexOf(iterator) when the function is invoked




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: