JavaScript AJAX Basics (retiring) AJAX and APIs Adding jQuery

Michael Pashkov
Michael Pashkov
22,022 Points

Can we use arrow functions?

Like $(document).ready(() => { $('button').click(() => { $(this).addClass("selected");
}); }); //end ready

instead of

$(document).ready(function () { $('button').click(function () { $(this).addClass("selected");
}); }); //end ready

Dave StSomeWhere
Dave StSomeWhere
19,786 Points

What happened when you tried it out?

Michael Pashkov
Michael Pashkov
22,022 Points

:) Interesting question, Dave. Why couldn't we use arrow function?

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,786 Points

Testing it out and checking the documentation is the best way to figure it out.

The key issue as stated in the MDN Arrow Function Doc

An arrow function does not have its own this; the this value of the enclosing lexical context is used i.e. Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope . Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the lexically enclosing function:

So, if you test it out (check out this test pen

And you see the following in the console (also the class will only be added in the regular function):

"regular this is [object HTMLButtonElement]"

"arrow this is [object Window]"