I'm trying to encapsulate some code in a class, but I can't access the 'this' object from within an event handler, since 'this' has the event target in it. function MyClass() { this.foobar="hello"; this.create=function() { var newSpan=document.createElement('span'); newSpan.innerHTML='sometext'; newSpan.onmouseup=this.SPANonmouseup; document.body.appendChild(newSpan); } this.SPANonmouseup=function (e) { alert(this.foobar); alert(this); } } Code (markup): The first box reads 'undefined', the second reads '[object HTMLSpanElement]'. How can I access the class variables from an encapsulated event handler?
I found the solution. Declare a private variable within the class, and assign 'this' to it in the constructor. Private variables have scope in all class functions: function MyClass() { [b]var t=this;[/b] this.foobar="hello"; this.create=function() { var newSpan=document.createElement('span'); newSpan.innerHTML='sometext'; newSpan.onmouseup=this.SPANonmouseup; document.body.appendChild(newSpan); } this.SPANonmouseup=function (e) { alert(t.foobar); } } Code (markup):