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?
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);
}