Task #87758
closedEvaluate function syntax style of TypeScript class functions
0%
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.
Updated by Andreas Kienast almost 6 years ago
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.
Updated by Markus Klein almost 6 years ago
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(); }
Updated by Markus Pircher over 5 years ago
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();
}
Updated by Andreas Kienast almost 4 years ago
- 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.