Task #87758
closed
Evaluate function syntax style of TypeScript class functions
Added by Frank Nägler almost 6 years ago.
Updated almost 4 years ago.
Category:
Backend JavaScript
Description
In TypeScript files, we currently use two different kind function syntax in classes.
Variant 1)
class Foo {
public bar = (baz: string): void => {
}
}
Variant 2)
class Foo {
public bar(baz: string): void {
}
}
We should use only one style and add it to tslinter if possible.
I would prefer variant 2, because of better reading.
- Description updated (diff)
In general, we should use variant 2, unless we want to use a method as a event callback, then variant 1 is necessary. The reason is, that each variant has a different binding of this
.
Variant 1¶
this
is bound to the class instance. The event target is still accessible via e.target
or e.currentTarget
, where e
is the Event
object being passed to the callback.
Example:
class Foo {
constructor() {
$(document).on('click', 'a', this.blockAll);
}
private blockAll = (e: JQueryEventObject): void => {
// this instanceof Foo
e.target.preventDefault();
}
Variant 2¶
this
is either bound to the class instance or the event delegate. In case of an event delegate, accessing this
in class context isn't possible anymore.
I would refrain from using arrow functions (var 2) as first citizens in a class.
If you need a method in an event handler simply introduce a local arrow function to avoid the this
binding.
class Foo {
constructor() {
$(document).on('click', 'a', () => this.blockAll());
}
private blockAll(e: JQueryEventObject): void {
// this instanceof Foo
e.target.preventDefault();
}
Markus Klein wrote:
I would refrain from using arrow functions (var 2) as first citizens in a class.
If you need a method in an event handler simply introduce a local arrow function to avoid the this
binding.
[...]
You can also manual bind:
class Foo {
constructor() {
$(document).on('click', 'a', this.blockAll.bind(this));
}
private blockAll(e: JQueryEventObject): void {
// this instanceof Foo
e.target.preventDefault();
}
- Status changed from Accepted to Closed
No progress here for almost two months. I'll close this issue now. If you think this decision is wrong, feel free to ping me to re-open the ticket.
Also available in: Atom
PDF