Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
How to have extensible event handler methods in a JavaScript class?

I have a JavaScript class that runs code when a click occurs. To make that code extensible, I've put it in a separate handleClick() method.

However, that's not working ideally because I can't access properties of the class instance via this. In the snippet below, this.bar is undefined when handleClick() is being called.

class Foo {
  constructor() {
    this.bar = 42;
    window.addEventListener("click", this.handleClick);
  }

  handleClick() {
    console.log("doing something", this.bar);
  }
}

new Foo();

How to fix this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To avoid the undefined issue, create a new property that holds a bound version of the event handler function using Function.prototype.bind() and use that as the event listener. In the snippet below, that's the handleClickFn property:

class Foo {
  constructor() {
    this.bar = 42;
    window.addEventListener("click", this.handleClickFn);
  }

  handleClickFn = this.handleClick.bind(this);
  handleClick() {
    console.log("doing something", this.bar);
  }
}

new Foo();

Now the class can be extended and everything works as expected:

class Foo {
  constructor() {
    this.bar = 42;
    window.addEventListener("click", this.handleClickFn);
  }

  handleClickFn = this.handleClick.bind(this);
  handleClick() {
    console.log("doing something", this.bar);
  }
}

class FooChild extends Foo {
  handleClick() {
    console.log("doing something else", this.bar);
  }
}

new FooChild();

Another approach is to bind the listener to the class instance itself (this) and implement the special handleEvent() method that the browser calls automatically, as described in the MDN docs for addEventListener():

class Foo {
  constructor() {
    this.bar = 42;
    window.addEventListener("click", this);
  }

  handleEvent(e) {
    if (e.type === "click") {
      this.handleClick();
    }
  }

  handleClick() {
    console.log("doing something", this.bar);
  }
}

class FooChild extends Foo {
  handleClick() {
    console.log("doing something else", this.bar);
  }
}

new FooChild();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda