I'm having a hard time answering my question, and I think it's simply because "class" and "this" and other such terms are too generic for effective Googling.
Consider the following code:
function product (name) {
var _productName;
this.getProductName = function() {
return this._productName;
};
this.alertProductName = function() {
// This errors because `this` is a reference to the HTML <input> tag and not the class
alert(this.getProductName());
}
this._productName = name;
var $productButton = $('<input type="button" value="What is my name?" />');
$productButton.on('click', this.alertProductName);
$('body').append($productButton);
}
var widget = new product('Widget');
widget.alertProductName();
jQuery (or maybe Javascript itself) is resetting what the this keyword points to once product::alertProductName is called as a callback to an event. I can't find any other way to access a specific instance of this class from within a function used as a callback. It looks like Javascript used to have arguments.callee but that has been deprecated.
Does anyone know how I can access a specific instance of a class in this manner? If not, is there a better way to write this so that I don't have this problem to begin with?