this. Arrow Functions lexically bind their context so
this actually refers to the originating context.
Let’s take a deeper look at both of these implementations.
Keep in mind that ES5 references below generically mean pre-ES6.
If you like this post check, out my recent post on Component sharing via react-native-web and give me a follow on twitter:
Basic Arrow Function Syntax
We will get to some more concrete examples in a second, but let’s get this out of the way first.
You can see the basic syntax for a statement on line 3 and an expression on line 4. Note the line 4 equivalent on line 5. With single parameter functions, parentheses are optional(lines 8–9). No param function example on line 12.
Note the ES5 .map() function on line 12. An ES6 implementation on line 17 and a BETTER ES6 implementation on line 22.
Example 2(Expressions and Statements)
Se we have established that the syntax for ES6 Arrow Functions is superior to previous standards, now let’s take a look at the execution context implications.
In the past you may have chosen the common pattern of a top-level
thisfollowed by a nested web of
self=thisstatements. Check out this representation below.
Lines 4, 11 and 17 all offer ES5 implementations for managing existing execution context limitations. You can see on Line 24 the ES6 Arrow Function lexical this context.
So HOW exactly is ‘lexical this’ allowing us to pass execution context? By using ‘lexical scoping’. Lexical Scoping just means that it uses
thisfrom the code that contains the Arrow Function.
I think a good way to finish this article would be to sum up the overall state of functions in ES6. You will likely hardly ever see old school functions as ES6 begins to take hold:
- Constructor functions will hopefully be replaced by class declarations
- Functions as subroutines will be replaced by arrow functions
- Functions as methods will be replaced by method definitions
So that’s it for Arrow Functions in ES6. Let me know your thoughts and questions and give me a follow on twitter. Keep after it.