Long story short:
var o="before";
x = function() //this needs to be an anonymous function
{
alert(o); //the variable "o" is from the parent scope
};
o="after"; //this chages "o" in the anonymous function
x();
//this results in in alert("after");
//which is not the way i want/need it
in reality my code is somewhat more complex.
My script iterates through many html objects and adds an event listener each element.
I do this by declaring an anonymous function for each element and call another function with an ID as argument. that ID is represented by the "o"-variable in this example.
After some thinking I understand why it is the way it is, but is there a way to get js to evaluate o as i declare the anonymous function without dealing with the id attribute and fetching my ID from there?
My full source code is here: http://pastebin.com/GMieerdw
The anonymous function is on line 303.
You can try using a self-invoking function like this:
That should alert “o” at whatever value it was during the loop, instead of alerting the final value of “o”.
I hope this helps in some way.