Kanpeki Kanpeki - 1 year ago 64
jQuery Question

Saving "this" when binding a function from a class

I have a simple class in JavaScript:

function MyCounter() {
this.counter = 0;

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
instance. Obviously, it fails because
does not exist, because at the time on execution of bound handler
equals to event, not

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() {

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?

Answer Source

You can just use .bind():


.bind() creates a mini stub function that essentially does this for you:

var self = this;
$('#button').click(function() {
    return self.run();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download