1

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?

aloea
  • 191
  • 1
  • 12

1 Answers1

1

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);
}
Dan Gamble
  • 3,965
  • 1
  • 24
  • 44
  • This is a duplicate. Please check for dupes before posting an answer. –  Oct 11 '21 at 13:03
  • "*`this` is what called the function. In this instance an event called the function so `this` refers to the event."* That's not correct. `this` will actually be the element that the handler is bound to. – Felix Kling Oct 11 '21 at 13:05