JS: variable inheritance in anonymous functions - scope

Posted by tkSimon on Stack Overflow See other posts from Stack Overflow or by tkSimon
Published on 2010-05-10T21:44:11Z Indexed on 2010/05/10 22:14 UTC
Read the original article Hit count: 648

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about anonymous-function