Reputation: 887
In the example code, myOtherFunc prints the inherited canvas variable, but when one clicks on the canvas to call myFunc, this.canvas prints as undefined. Why is this?
HTML:
<!DOCTYPE HTML>
<html>
<body>
<canvas id="drawCanvas" style="border:1px solid #000000;"></canvas>
<script>
class myClass {
constructor() {
this.canvas = document.getElementById('drawCanvas');
this.ctx = this.canvas.getContext('2d');
this.canvas.addEventListener('click', this.myFunc);
this.myOtherFunc();
}
myFunc(event) {
console.log(this.canvas);
}
myOtherFunc() {
console.log(this.canvas);
}
}
let c = new myClass;
</script>
</body>
</html>
Upvotes: 1
Views: 61
Reputation: 9157
That's because the event handler's scope is the canvas, not the class. You need to bind this
to the event handler:
this.canvas.addEventListener('click', this.myFunc.bind(this));
For more information about bind
, see this MDN reference.
Upvotes: 1
Reputation:
There is also the really useful:
this.canvas.addEventListener('click', this);
If you pass an object instead of a function, then handleEvent in that object will be called, and the this will be the object. Inside handleEvent you can check the event.type to figure out the kind of event. An example:
class Foo {
constructor(element) {
this.element = element;
element.addEventListener("mousedown", this);
element.addEventListener("mousemove", this);
element.addEventListener("mouseup", this);
}
handleEvent(event) {
// all events come here, so lets redistribute them:
this[event.type](event);
}
mousemove(event) {
}
mousedown(event) {
}
mouseup(event) {
}
}
Upvotes: 3
Reputation: 1
this
is the <canvas>
element itself within click
event handler attached to the canvas
element. this
:<canvas>
does not have a .canvas
property set at element at code at Question, resulting in undefined
being logged at console
myFunc(event) {
console.log(this);
}
Upvotes: 2