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