Fortunately, this rule is not another arcane syntax exception, but a simplification taken from other languages to reduce the code in callback functions and manage “this” more logically.
ES6 Arrow Functions
With ES6, a callback function can be defined using the new “arrow function” syntax. This syntax allows you to get rid of the word “function” and put a literal “=>” arrow in between the parameter list and function body.
There are several syntax variations, depending on the number of arguments and lines of code in the function. No matter which syntax version you are using, though, they all flow from this basic form:
If you were to write the same callback function without the arrow syntax, it would look like this:
While it is possible to reduce the arrow syntax further, the difference between arrow functions and standard functions is insignificant when you look at the number of characters to type.
The real value in arrow functions is not in the syntax reduction, then, but in the way it manages “this” for you.
As a simple example, look at the following code and the arrow function within:
Note that there is no “that = this” hand-waving… no .bind, .call or .apply, either. There is nothing in this code to explicitly state what the value of “this” will be when “this.selectManager(employee)” is called.
The arrow function syntax uses the knowledge of where the code lives to see that it should use the value of “this” from the parent function. In other words, the value of “this” in the “addNewEmployee” function will also be the value of “this” inside of the arrow function callback for the event handler.
This has some tremendous benefits, as you can imagine. But this doesn’t solve every single riddle of “this”, and it doesn’t absolve you from the other rules either.
Changing The Surrounding “this” Changes The Arrow Function’s
When working with the code in the above “orgChart” example, the value of “this” within the addNewEmployee function is still managed by the standard rules of “this”. If you call the method in this manner:
Then the value of “this” within the “addNewEmployee” function and within the arrow function callback will be the “orgChart” object. However, if you change the invocation pattern for addNewEmployee, you will also change the value of “this” in both locations.
In this example, the standard function invocation pattern is used, leaving the value of “this” to be either the global object or undefined if your code is in strict mode. When the code gets to the callback for the “complete” event handler, the value of “this” will not be what you expect. The callback function will fail because “this” is not pointing at “orgChart”, and the “selectManager” method will not be found.
Worth 10x It’s Weight In Deleted Code
Master The Other 5 Rules
The content of both of these formats is the same. Each format includes all 5 core rules for managing “this”, and has been updated to includes the above content as email / chapter 6!