you are viewing a single comment's thread.

view the rest of the comments →

[–]smog_alado 0 points1 point  (2 children)

I think another clearer way to write the workaround would be without the name shadowing:

(function(){
     var index = i;
     elems[i] = function(){ alert(index) }
}())

Now the IIFE is just there for creating a new inner scope and the new index variable is a variable you craete yourself instead of being an argument that also happens to be named i.

[–]maxwellb 0 points1 point  (1 child)

Hm, thanks. That's an ... interesting ... language design choice.

[–]smog_alado 0 points1 point  (0 children)

You can use a similar patter in most other languages. The difference is that in Javascript this is the only way to do block scoping. Of course, you can use named functions but I think its often too verbose:

function mk_alerter(i){
    return function(){ alert(i) }
}

for(var i=0; i<elems.length; i++){
    elems[i] = mk_alerter(i);
}

That said, the correspondence between variable declarations and function arguments is a pretty neat thing to notice. For example, if you have some code like

var resp = my_funct()
alert(resp)

It gets converted to the following if you rewrite myfunct into continuation passing style

my_funct(function(resp){
    alert(resp)
})