I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.
function foo(id) {
this.dom = document.getElementById(id);
this.bar = 5;
var self = this;
this.dom.addEventListener("click", self.onclick, false);
}
foo.prototype = {
onclick : function() {
this.bar = 7;
}
};
Now when I create a new object (after the DOM has loaded, with a span#test)
var x = new foo('test');
The 'this' inside the onclick function points to the span#test and not the foo object.
How do I get a reference to my foo object inside the onclick function?
this is one of the most confusing points of JS: the 'this' variable means to the most local object... but functions are also objects, so 'this' points there. There are other subtle points, but i don't remember them all.
I usually avoid using 'this', just define a local 'me' variable and use that instead.