Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving "this" when binding a function from a class

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?

like image 376
Kanpeki Avatar asked Jul 23 '26 16:07

Kanpeki


1 Answers

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();
});
like image 63
jfriend00 Avatar answered Jul 26 '26 06:07

jfriend00