I've written a constructor function that registers an event handler:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1200);
}
};
// called as
var obj = new MyConstructor('foo', transport);
However, I am unable to access the created object's data property within the callback. It appears that this does not refer to the object that was created, but to another.
I also attempted to use an object method rather than an anonymous function:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
However, it has the same issues.
How do I get to the right object?