user784540
user784540

Reputation:

How to get the current object reference in a class method?

Usually I develop on Java, and now I am studying JavaScript/HTML5 Canvas things. And I get a strange situation from Java developer's point of view.

There's a html5 canvas object on the html page, and I want to track the mouse click events on this canvas.

I declared class GameBoard and initialized its properties:

function GameBoard() {
  // defining a property for GameBoard class instance
  this.myProperty = 'some text here';

  // getting canvas element
  this.boardCanvas = document.getElementById("myCanvas");

  // setting the mouse click event listener
  this.boardCanvas.addEventListener("mousedown", this.handleMouseClick, false);
}

and there's a class method to handle mouse click events:

GameBoard.prototype.handleMouseClick = function(event) {

     alert(this.myProperty);

}

handleMouseClick() will display undefined because this in handleMouseClick() method refers to the HTML5 Canvas instance (boardCanvas).

My question: how can I refer the current GameBoard class instance inside of handleMouseClick method to get myProperty field value defined in the class constructor?

What I am doing wrong here?

Thank you.

Upvotes: 4

Views: 5744

Answers (2)

haim770
haim770

Reputation: 49095

One of the common conventions is to use an alias to this, usually with a variable named self:

function GameBoard() {
    // defining alias
    var self = this;

    this.myProperty = 'some text here';
    this.boardCanvas = document.getElementById("myCanvas");

    this.handleMouseClick = function()
    {
        // using alias
        alert(self.myProperty);
    };

    this.boardCanvas.addEventListener("mousedown", this.handleMouseClick, false);
}

However, since you're defining the method on the prototype here, you can either use bind (as proposed by @Alexander) or try this:

var self = this;

this.boardCanvas.addEventListener("mousedown", function(e)
{
    // calling the function with 'self/this' context
    self.handleMouseClick(e);
}, false);

(Thanks to @Alexander for his contributions)

Upvotes: 2

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can use bind in order to set this for function

  this.boardCanvas.addEventListener("mousedown", this.handleMouseClick.bind(this), false);

Example: http://jsbin.com/vutugi/1/

Upvotes: 2

Related Questions