Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!