I have a simple class in JavaScript:
function MyCounter() {
this.counter = 0;
$('#button').click(this.run);
}
MyCounter.prototype.run = function() {
this.counter += 1;
return console.log(this.counter);
};
This class is invoked like that:
var myCounter = new MyCounter();
HTML includes a single clickable button with ID="button". Clicking this button is supposed to increment an internal variable inside a myCounter instance. Obviously, it fails because this.counter does not exist, because at the time on execution of bound handler this equals to event, not myCounter instance.
A crude hack to overcome this is to save "this" to some other variable and wrap calling actual handler into a anonymous function:
function MyCounter() {
this.counter = 0;
var this2 = this;
$('#button').click(function() {
this2.run();
});
}
Is there a better, cleaner way? Or at least, may be there's an universal agreement / style guide on how to name such "temporary this" variables?
You can just use .bind():
$('#button').click(this.run.bind(this));
.bind() creates a mini stub function that essentially does this for you:
var self = this;
$('#button').click(function() {
return self.run();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With