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

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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