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

178
Views
Use a class method to set a listener callback with 'this' being the class instance that ran the method

Here's what I'm trying to do:

class foo{
  constructor(){
    this.num = 1;
    }
  log() {console.log(this.num)}
  assign() {
      document.querySelector('div').onclick = this.log
  }
}

let bar =  new foo();
bar.assign()

/* Click */ // goal: 1, actual: undefined
<div>Click Me</div>

When the class method runs, its scope is the HTML object itself, so this.num doesn't exist. How can I link the this of the callback to the class instance that set the listener, in this case bar

about 4 years ago · Juan Pablo Isaza
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!