(Instructions on how to run the code are available in the Github page.)
The problem with “this” – Example # 1
Run Example # 1 in your terminal with the following command: node example-1.js. The result of this is: “THE MESSAGE IS: undefined“.
So, we need a way to reference the “tools” object inside of the anonymous function that we passed to the setTimeout method. Well, the best approach is still to reference the “this” keyword. A common and popular approach in the past has been to set a reference to “this” before calling the setTimout method. For example: “var me = this;”. Okay, so while that is still a possible technique, there now is a far more elegant approach.
Fat arrow functions solve the “this” problem – Example # 2
Run Example # 2 in your terminal with the following command: node example-2.js. The result of this is: “THE MESSAGE IS: Hello from this.message!”
Fat Arrow Function – One Argument – Example # 3A
Fat Arrow Function – Multiple Arguments – Example # 3B
A few things to keep in mind:
- In Example # 2, the fat arrow function takes no arguments, but, it still has a pair of opening and closing parentheses. This is because when a fat arrow function takes no arguments, you must include a pair of opening and closing parentheses.
- In Example # 3A, there are no parentheses in the fat arrow function. This is because when there is one argument, you do not need to include parentheses.
- In Example # 3B, there are two arguments contained inside of parentheses. This is because when there is more than one argument, you must include parentheses.
In this article we saw that fat arrow functions solve the “this” problem because they provide access to the object to which the containing function belongs, and you can access that object at all times by using the “this” keyword. And even when nesting fat arrow functions, the “this” reference is preserved, eliminating the need to set a temporary reference to “this”. Just keep in mind the importance of how the syntax can differ, depending on the number of arguments that the fat arrow function takes. In other words, with zero or multiple arguments, parentheses are required, and with only one argument parentheses are not required. Pretty simple, once you get used to it.