Task #87758

Evaluate function syntax style of TypeScript class functions

Added by Frank Naegler 3 months ago. Updated 3 months ago.

Status:
Accepted
Priority:
Should have
Assignee:
-
Category:
Backend JavaScript
Target version:
-
Start date:
2019-02-21
Due date:
% Done:

0%

TYPO3 Version:
10
PHP Version:
Tags:
Complexity:
Sprint Focus:

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.

History

#1 Updated by Frank Naegler 3 months ago

  • Description updated (diff)

#2 Updated by Andreas Fernandez 3 months 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.

#3 Updated by Markus Klein 3 months 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();
  }

#4 Updated by Markus Pircher 3 months 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();
  }

Also available in: Atom PDF