0

I have this js code , when it executes "user clicked" effectively gets printed but an error is thrown when trying to execute funA:

app.js:13 Uncaught TypeError: this.funA is not a function at HTMLBodyElement.handleclick (app.js:13:14)

I guess the interpreter hasn't read the funA function yet at the time of executing handleclick? What happens here and how could I solve this.

class UI {
    constructor() {
        this.body = document.querySelector("body")
        this.body.onclick = this.handleclick
    }

    funA() {
        console.log("called funA")
    }

    handleclick(e) {
        console.log("user clicked")
        this.funA()
    }
}


new UI()

1 Answers1

0

When you set the function like that, the body element has the context of this.

Save the context of this with the .bind function

class UI {
    constructor() {
        this.body = document.querySelector("body")
        this.body.onclick = this.handleclick.bind(this);
    }

    funA() {
        console.log("called funA")
    }

    handleclick(e) {
        console.log("user clicked")
        this.funA()
    }
}


new UI()
body { width: 100%; height: 100vh; }
<p>lorem ipsum</p>
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34