JS: variable inheritance in anonymous functions - scope
- by tkSimon
hey guys, someone from doctype sent me here.
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