Can someone explain where my thinking goes wrong here ? I have a class that adds a mousedown event listener to a specified canvas. I make two instances of the class attached to two different canvases. I expect to get responses from both instances but all responses say they're from the second instance.
class Mycanvas{
constructor (canvas,name){
self = this;
this.name=name;
canvas.addEventListener('mousedown', mousedown);
}
function mousedown(){console.log(self.name)}
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');
BUT, this code works fine :
class Mycanvas{
constructor (canvas,name){
this.name=name;
canvas.addEventListener('mousedown', ()=>console.log(this.name));
}
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');
You invoke Mycanvas(canvas1,'1') directly (without the new keyword), which, I believe, only calls its constructor without instanciating a new Class. This doesn't output the expected result and makes you believe you need the self=this hack. But classes work like this :
class Mycanvas{
constructor (canvas, name){
this.name=name;
this.canvas = canvas;
}
logMyName() {
this.canvas.addEventListener('mousedown', () => console.log(`My name is ${this.name}`));
}
}
let mycanvas1 = new Mycanvas(canvas1,'1');
mycanvas1.logMyName();
let mycanvas2 = new Mycanvas(canvas2,'2');
mycanvas2.logMyName();
canvas {
border: grey solid 1px;
width: 50px;
height: 50px;
cursor: pointer;
}
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>