0

I wonder why if i declare a function outside the listener function, this will be undefined but if i delcare the function inside the listener function this will be defined..

working:

someClass.each(function(i) {
  someClass.eq(i).on('click', (e) => {
    var targetClass = this.classList[0],
    console.log(targetClass);
  });
}); // this will be defined as the clicked class

not working:

someClass.each(function(i) {
  someClass.eq(i).on('click', buttonClick)
}); 
buttonClick = (e) => {
    var targetClass = this.classList[0],
    console.log(targetClass);
}); // this will be undefined
Kemal Dwiheldy
  • 409
  • 1
  • 4
  • 14
  • 1
    you need to understand how `this` works inside an arrow function – Jaromanda X Jun 16 '18 at 01:13
  • 1
    `this` works differently (or not at all) for arrow functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Brett Commandeur Jun 16 '18 at 01:13
  • 1
    see this answer https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6 – Jaromanda X Jun 16 '18 at 01:14
  • `someClass.each` looks like jquerey - so this in the callback (I think) is the current item in `someClass` - i.e. if you were to `someClass(function(i, x) {` ... this would be `x` - which is why your first code works and the second does not – Jaromanda X Jun 16 '18 at 01:15
  • note, your first code would also fail if you wrote it like `someClass.each(i => {` – Jaromanda X Jun 16 '18 at 01:16

2 Answers2

2

Use non-arrow functions for methods that will be called using the object.method() syntax. Those are the functions that will receive a meaningful this value from their caller.

Arrow Functions lexically bind their context so this actually refers to the originating context. So you can't use arrow functions in those scenarios.

Source (Especially the "What’s this?" section)

More sources

trinaldi
  • 2,872
  • 2
  • 32
  • 37
0

The scope changes when you enter that anonymous closure and in your second function 'this' points to the Object outside the buttonClick function. You can do the following to make your code work,

buttonClick = (e) => { // I'm assuming e = event object
    var targetClass = e.currentTarget.classList[0], 
    console.log(targetClass); 
}); 
Ajanth
  • 2,435
  • 3
  • 20
  • 23