Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
DIfferentiating between multiple event listeners

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');
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!