0

I have the following code snippet:

VIEW.CTX = function(canvas){
    this.canvas = canvas;
    this.canvas.onmousedown = this.onDocumentMouseDown;

    //more stuff...
};

VIEW.CTX.prototype = {
    constructor: VIEW.CTX
};

and later

VIEW.CTX.prototype.onDocumentMouseDown = function(event){
    console.log(this);
    this.doSomething();
}

When I create an instance of CTX and call onDocumentMouseDown directly:

var ctx = new VIEW.CTX(theCanvas);
ctx.onDocumentMouseDown('');

'this' refers to my instance of CTX. However, when I invoke onDocumentMouseDown by clicking on the canvas, 'this' refers to the canvas element, and I get an error when it tries to call this.doSomething();. How do I make it refer to its instance of CTX instead of the canvas element?

Justin
  • 1,881
  • 4
  • 20
  • 40
  • The solution is `this.canvas.onmousedown = this.onDocumentMouseDown.bind(this)` or store the constructor `this` in a variable (`var that=this;`) and do `...onmousedown = function(e) { that.onDocumentMouseDown(e); }` I'll see if I can find the most appropriate duplicate. – apsillers Oct 13 '14 at 19:20
  • @aspillers Your .bind() solution worked for me. You should post it as an answer. – Justin Oct 13 '14 at 19:29

0 Answers0