|
|
|
|
|
by genrez
1884 days ago
|
|
I agree that inheriting the `this` for arrow functions is beneficial. To me it seems like you would want to use the normal syntax for global functions for hoisting and to prevent unintentional re-definitions, the arrow functions where you would use lambda functions in other languages, and the class method syntax for methods. side-note: Most of my JS experience is writing userscripts for myself, so I definitely do my share of 'this' shenanigans. |
|
Take the following example, which is a normal class method:
> alertSum() { alert(this.a + this.b); }
And here we have an arrow function used to create an instance method (just an arrow function assigned to a property on the instance):
> alertSum = () => { alert(this.a + this.b); }
Then let's say we want to pass the method directly as callback:
> this.button.addEventListener('click', this.alertSum)
The first example (class method syntax) won't have the necessary `this` context unless it has its context bound to the instance through `Function.prototype.bind`. There are other patterns to avoid this (e.g. wrapping all callbacks in arrow functions when passing them), but it's useful to consider that classes methods can easily create confusion because that's _exactly where_ someone more used to a different language may assume the `this` context is bound lexically.