Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can wrap the assignment in a function, or the right-hand side at least:</p> <pre><code> objects[i].callback = (function(i) { return function(e, x, y) { cb(e, x, y, i); })(i); </code></pre> <p>The "outer" anonymous function is called right away, copying the loop variable "i" into an argument (which I also called "i"; some think it's confusing to do that while others say it's confusing <em>not</em> to do it, so you can decide :-) which is then used by the returned "inner" anonymous function.</p> <p>Another approach to this problem would be to use a utility function for this purpose instead of a simple in-line anonymous function. In this case, it's made slightly tricky because you want "i" to be the <em>last</em> parameter of the actual callback function. The <a href="http://osteele.com/sources/javascript/functional/" rel="nofollow">Functional</a> JavaScript library has a cool utility that lets you "pre-populate" selected arguments of a function with fixed values, giving you a function that lets you pass in arguments to the non-fixed ones; it'd look something like this:</p> <pre><code> objects[i].callback = (function(e, x, y, i) { return cb(e, x, y, i); }).partial(_, _, _, i); </code></pre> <p>Whether that's better or worse is a matter of style and opinion.</p> <p><em>edit</em> just had a little more coffee - I think that I was being a little silly thinking that I had to use "partial()" above. The fact that the inner (the "real" function) wants "i" at the end of the parameter list is really not relevant to the way things need to be set up. That above example could also be done like this:</p> <pre><code> objects[i].callback = (function(i, e, x, y) { return cb(e, x, y, i); }).curry(i); </code></pre> <p>which is way less bizarre. (Either would work however. At least, I think they would. :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload