0

I have the following event handler defined:

$('#current-tab').click(myCode.handleTabClick);

And in that function I have

handleTabClick: (): void => {
    const identifier: string = $(this).attr('id');
},

When I execute this in the browser, the event gets fired but I see identifier is "undefined". However, if I add a break-point and then copy $(this).attr('id') into the browser's console, I see that this resolves to "current-tab".

Why can't I capture this into my constant variable?

DrGriff
  • 4,394
  • 9
  • 43
  • 92
  • Can you create a minimal reproducible example? It is very hard to tell from the information you provided. – AhmerMH Dec 08 '20 at 16:37
  • 2
    Handle click is an arrow function. Change it to a regular function. The “this” context is not bound to the function in an arrow function – Faraz Dec 08 '20 at 16:38
  • Check [this](https://stackoverflow.com/a/27670450/10606400) answer. – Swati Dec 08 '20 at 16:39
  • https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable – epascarello Dec 08 '20 at 16:46

1 Answers1

1

Change:

handleTabClick: (): void => {
    const identifier: string = $(this).attr('id');

},

To:

handleTabClick: function(): void {
    const identifier: string = $(this).attr('id');
}

In a an arrow function this is not bound to the function

DrGriff
  • 4,394
  • 9
  • 43
  • 92
Faraz
  • 433
  • 3
  • 7