Oh yes, isn't it beautiful? A TypeScript CodeBase, well maintained.... and then this. Somebody starts to use only named arrow functions in classes. Because it is "the new way". What a colossal bullshit. Of course arrow functions are cool. They offer a wide range of possible uses in the most diverse cases.
() => {
// some code
}
Such a call can be perfectly used to describe return functions without overhead.
It can be perfectly adapted for various use cases without making the code confusing.
However, what makes absolutely no sense and creates confusion is the following:
public functionName = () => {
// some code
}
Such a case is syntactically correct, but it is absolutely confusing and unpleasant, if it can be done this way, too:
public functionName() {
// some code
}
Unfortunately, I see this kind of buck crap more and more often in the wild. I hope to reach and save at least a few lost souls with this little rant.
Kind regards,
Yours, Josun
Top comments (2)
There is a good reason to use the arrow syntax in class definitions, since it allows binding
this
to the class instance. In classes, this is quite useful, since there is no closure available to access the instance otherwise.Consider a simple example like:
In this case, calling the
identify()
method on the instance works as expected:It works because
this
is bound to the object being accessed with the property accessor (.
). If you were to assign the method to a variable and call it,this
context would change:this
is set to the global context, which in the browser's case would bewindow
, which means it would evaluate aswindow.name
. In previous versions of JavaScript, you could bindthis
to the function in the constructor to fix this:Now this code would work:
This can get quite verbose and hard to maintain, so the alternative is to use an arrow function to assign a function to the property to achieve the same thing. The trick is that arrow functions automatically bind
this
to the lexical scope, which normal function assignments don't:This way,
this
will always refer to the instance ofMyThing
, just like it would had it been bound to the instance in the constructor:Understanding this is the key to deciding when to use this feature, so it's not completely pointless in all cases, as you state in your article. This is especially important in JSX where setting an event handler to a property of an object might make the method lose its
this
context, rendering it useless as an instance method:I think arrow function for new learners are pretty much complicated for them, but with time they can do it easily, just like I did!