0

How to make:

$('.x').on('click', function() {
    console.log($(this).attr('id'));
});

like that:

$('.x').on('click', () => {
    console.log($(this).attr('id'));
});

but still working?

Freezend
  • 11
  • 2

1 Answers1

0

You could use event parameter which is supplied to the function, and event.target will be equal to this call in regular function.

$('.x').on('click', (event) => {
    console.log($(event.target).attr('id'));
});

The reason you can't use this is shown below. Link I previously provided shows how complex can be binding of context to arrow function. Jquery uses similar approach for your handlers

var customObject = {
  data: "test"
}

function test(func) {
  func.call(customObject);
}

test(function () 
{
  console.log(this);
});

test(() => {
  console.log(this);
});
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40