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

181
Views
How event handler inside JavaScript class/function got called?

I'm quite new on JS and got stuck on this problem. So I have this constructor which I understand how its works EXCEPT for one thing. How does an event handler got called from inside of an object or function?

I thought event handler could only be placed on global scope directly, not inside a function/object or another block scopes.

class Counter {
    constructor(element, defaultValue) {
       this.element = element;
       this.value = defaultValue;

       this.valueDOM = element.querySelector('.value');
       this.valueDOM.textContent = this.value;

       this.increase = this.increase.bind(this);
       this.btnIncrease = element.querySelector('.increase');
       this.btnIncrease.addEventListener('click', this.increase);
    }
    increase() {
       this.value++;
       this.valueDOM.textContent = this.value;
    }
}

const counterOne = new Counter(document.querySelector('.counter-one'), 0);
const counterTwo = new Counter(document.querySelector('.counter-two'), 0);

The HTML is quite simple, just a plain old counter like this.

<div class="container counter-one">
    <span class="value">0</span>
    <button class="increase">+</button>
</div>
<div class="container counter-two">
    <span class="value">0</span>
    <button class="increase">+</button>
</div>
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

addEventListener in this case is pointing directly at the local object's this.increase method. It is not pointing at the object's prototype function, but an actual distinct copy of that function which is attached to the object instance. Does that help?

about 4 years ago · Santiago Gelvez 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!