Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
how does the javascript interpreter work in classes

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()

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda