DEV Community

'this' and arrow functions

Kelvin Wangonya on August 26, 2018

Arrow functions were introduced in ES6 as a new syntax for writing Javascript functions. Thanks to their short syntax, they encourage the use of sm...
Collapse
 
codevault profile image
Sergiu Mureşan

The problems are not limited to event handlers, JQuery's utility functions are also affected by this. The project I am working on relies on JQuery quite a bit so I am defaulting to regular functions and, when need be, I am using arrow functions.

I like the event handler example here, really helps understand what is up with arrow functions. I wonder if that's why the newer JS functions pass the element you are checking through their arguments instead of through this.

Collapse
 
wangonya profile image
Kelvin Wangonya

Hi! Thanks for reading. Yeah, the problems certainly aren't limited to what I've written here. For example, they also can't be used as constructors.

"I wonder if that's why the newer JS functions pass the element you are checking through their arguments instead of through this." Which newer functions are you referring to?

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

Nevermind, I always thought that some of the array functions like filter and some are from ES2015 which, on further investigation, turned out to be false

Although, they work nicely with the arrow functions since they all take their values not from this but from the parameter of the functions you give it.

Collapse
 
kayis profile image
K

Yes, the capturing of this by arrow functions is rather cumbersome.

Somehow I managed to use it either in a functional programming context where there is no this needed or with classes and class fields, where I can write something like class A { x = "world!"; m = () => "Hello, " + this.x; }.

Collapse
 
wangonya profile image
Kelvin Wangonya

Nice! Maybe you should do an article on that when you find the time. Expound on it a little more, I'd be interested (or have you already?).

Thanks for reading

Collapse
 
kayis profile image
K

On what specifically?

Collapse
 
anurbol profile image
Nurbol Alpysbayev • Edited

Just use VSCode and utilize Intellisense. You'll be given appropriate hints and gradually you'll learn all the quirks (not actually) of this.

Collapse
 
wangonya profile image
Kelvin Wangonya

Hi! Thanks for the tip.

Collapse
 
neelam28 profile image
Neelam

Thanks so much for this post. I now have a clear(somewhat, as "this" is very complex to understand) idea about the relationship between arrow functions and the "this" keyword :)

Collapse
 
hasheendeberry profile image
Hasheen DeBerry

Very helpful. Thank you!

Collapse
 
wangonya profile image
Kelvin Wangonya

I'm glad you found the post useful Hasheen. Happy coding!