Javascript get reference to parent object/class from event handler
You need to bind the function's context; otherwise this
will be the global object:
$('element').click($.proxy(this.eventHandler, this));
In a modern browser you can also use Function.prototype.bind
:
$('element').click(this.eventHandler.bind(this))
function Foo() {
var _self = this;
this.num=0;
$('element').click(this.eventHandler);// jQuery to attach an onclick event to my element.
this.eventHandler=function() {
_self.num++;
}
}
use a reference _self = this
defined in the outer scope