0

Im having trouble reaching my object from a nested function. Ill just go right ahead and show the code.

function ChartObject(parent){
    this.CANVAS = document.createElement('canvas');
    parent.appendChild(this.CANVAS);

this.CANVAS.addEventListener('mousemove', function(evt){
var ctx = this.CANVAS.getContext("2d");//cannot access the CANVAS like this
//do stuff
}, false);

}

Ok so my problem is i cannot access the canvas object from the line: var ctx = this.CANVAS.getContext("2d");//cannot access the CANVAS like this

MrRed
  • 567
  • 1
  • 5
  • 17

1 Answers1

0

Inside the event handler bound to this.CANVAS the canvas would be only this, as it is the bound element

function ChartObject(parent){
    this.CANVAS = document.createElement('canvas');
    parent.appendChild(this.CANVAS);

    this.CANVAS.addEventListener('mousemove', function(evt){
        var ctx = this.getContext("2d");
    }, false);

}
adeneo
  • 293,187
  • 26
  • 361
  • 361
  • Wow thanks for the fast reply. Great job explaining it i understand this alot better now. I will accept as correct once 7 minuites has elapsed. Appreciate it – MrRed Oct 20 '16 at 14:29
  • But say i need to get hold of the ChartObject becuase it has other variables other than this.CANVAS which is easy to get hold of? – MrRed Oct 20 '16 at 14:32
  • Not quite sure what you mean? You can return anything from the function, or make a reference to the function and access it's properties? – adeneo Oct 20 '16 at 14:38
  • Ok so imagine in my chart object uner this.CANVAS = document.createElement i have another variable like this.JSON. from the function(evt){} code i cannot access this.JSON – MrRed Oct 20 '16 at 15:27
  • So baically i must create a SELF = this variable right in the ChartObject and from the nested addEventListener function call SELF.JSON instead of this.JSON.. Wow.. Javascript seems so weird compared to other languages. Terrible design no? – MrRed Oct 20 '16 at 15:32
  • Yes, the easiest would be to use a variable to reference the outer this-value, like `self`, or jus a variable to hold the JSON, whatever fits -> https://jsfiddle.net/adeneo/90gu23rk/ – adeneo Oct 20 '16 at 15:33
  • Ok brilliant. Thanks for the jsfiddle thats a nice touch. You really helped me out, thanks bud. 2 billion upvotes to you sir – MrRed Oct 20 '16 at 15:36