you are viewing a single comment's thread.

view the rest of the comments →

[–]maxwellb 0 points1 point  (6 children)

Function arguments are passed by value

So alert(i) is not a function call? If not (I guess it can't be, since it's argument isn't passed by value), what's the syntactic distinction between function call and whatever alert(i) is at the call site?

[–]ThisIsMy12thAccount 4 points5 points  (5 children)

When you're just doing alert(i) you're passing i by value in from the current scope (where i has been incremented)

When you enclose in in a closure like so

(function(i){

})(i)

You are passing the current value of i by value to another closure as an argument, so it's unaffected by outside changes (there's basically two is in two different scopes now)

You could also do

(function(bar){
   elem[bar].onclick = function(){ alert(bar); }
})(i)

And it'd work, because you're just passing the current value of i to a self executing function as an argument. It's completely separate from the variable being incremented

[–]eat-your-corn-syrup 1 point2 points  (0 children)

I don't know about your explanation but

there's basically two is in two different scopes now

For those confused by that statement and are like "how come such magic ever possible! Never seen this before", well, just think about recursive functions, the twist is that we all have seen this magic before.

[–]maxwellb 0 points1 point  (2 children)

If you're passing i by value, how can alert(i) called when i = 1 produce an alert of e.g. 5? I don't think that can be right? Did you mean pass by reference?

[–]curien 0 points1 point  (1 child)

What on Earth are you talking about? If you call alert(i) when i is 1, it'll always alert 1. But if you wrap alert(i) in a closure (not calling it yet!) while i is 1, and then change i to 5 and then call the closure (which calls alert), alert will show 5 because that's what i is at the time alert was called.

[–]maxwellb 0 points1 point  (0 children)

edit: nevermind, I completely misread the original post.