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

131
Visualizações
Different values of "this" in event handlers

Consider this piece of TypeScript code which relies on the JQuery library:

class Alpha {
    public foo() {
        $('.ca').click(() => {console.log(this)});
        $('.cb').click(function () {console.log(this)});
    }
}

Assume that $('.ca') and $('.cb') refer to two buttons.

After calling foo on an Alpha object, we see that the click handler for '.ca' prints the Alpha object, whereas the click handler for '.cb' prints the button identified by $('.cb').

Both of these different interpretations of this can be useful. But what do I do if I want to use both versions of this inside a handler? In other words, I want to access both the Alpha object and the '.cb' button inside the handler.

EDIT

To clarify: I should have emphasized that I'm specifically interested in a way to access the '.ca' button in the situation where I'm using the => notation.

User Matt U indicated this in his answer to my question.

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

0

You can use the event object with the arrow function to get the element (e.g. the button with class .cb) that triggered the click event, while this will refer to the class. Such as:

class Alpha {
  foo() {
    $('.cb').click(event => {
      console.log(this);
      console.log(event.target.className);
    }
  }
}

See here for a working example.

about 4 years ago · Juan Pablo Isaza Relatório

0

Why it works like that can be answered with this.

TLDR : Inside event handlers, this is the element on which the event is attached. All function types (except arrow functions), this depends on how they are invoked and belong to the invoker. Arrow functions take this from the lexical scope of their declaration (Here the object instance).

You can keep a reference of the this in another variable, and taking advantage of closures use that inside your event handler.

class Alpha {
    public foo() {
        let context = this;
        $('.ca').click(function () {
        console.log(context); console.log(this); });
    }
}
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