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

186
Views
Javascript class this.x is not a function when calling function from inside class

I have a button which, when pressed, should call a function which calls another function. this is inside a class.

class cat{
    constructor(){
        this.event_listener();
    }

    log_2(){
        console.log("cat 2");
    }
    log_1(){
        console.log("cat 1");
        this.log_2();
    }

    event_listener(){
        document.getElementById("cat_button").addEventListener("click", this.log_1);
    }
}

let cat1 = new cat();

The first function, this.log_1(), is called when the button is pressed and outputs "cat 1" as expected, but then the error

this.log_2 is not a function

appears on the console, although log_2() is defined within the class. How can I structure this so that log_2() is recognised as a function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

this is what called the function. In this instance an event called the function so this refers to the event.

What you'll want to do is bind the method before using is as a reference. Now this will refer to the instance of the class.

event_listener(){
  this.log_1 = this.log_1.bind(this)

  document.getElementById("cat_button").addEventListener("click", this.log_1);
}
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!