This is weird at first glance to me because while, yes, you're passing in o to the closure, when you set o to {x: 'bar'}, which o are you talking about; is it the o outside the function?
This becomes a bit more of a scoping issue. But the solution is that the o inside the function is still a separate variable from the o outside the function, because it was "declared" separately as an argument (function(o)). So the final output is still { p: 'foo' }
If you change it to this:
varo={p:'foo'};(function(z){//note now we've declared 'z', and there's no 'o' in the inner functiono={x:'bar'};//because there's no 'o' inside here, we use the 'o' defined in line 1})(o)console.log(o);
o gets changed! Because it was never redeclared inside the function. So the final output here is: { x: 'bar' }
Interesting distinction, and thanks for clearing that up!
I was curious what would happen if you did something like this
This is weird at first glance to me because while, yes, you're passing in
oto the closure, when you setoto{x: 'bar'}, whichoare you talking about; is it theooutside the function?This becomes a bit more of a scoping issue. But the solution is that the
oinside the function is still a separate variable from theooutside the function, because it was "declared" separately as an argument (function(o)). So the final output is still{ p: 'foo' }If you change it to this:
ogets changed! Because it was never redeclared inside the function. So the final output here is:{ x: 'bar' }This has nothing to do with pass-by-reference issue! it's about scoping