Project

General

Profile

Actions

Task #87758

closed

Evaluate function syntax style of TypeScript class functions

Added by Frank Nägler about 5 years ago. Updated over 3 years ago.

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

0%

Estimated time:
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.

Actions #1

Updated by Frank Nägler about 5 years ago

  • Description updated (diff)
Actions #2

Updated by Andreas Kienast about 5 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.

Actions #3

Updated by Markus Klein about 5 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();
  }
Actions #4

Updated by Markus Pircher about 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();
  }

Actions #5

Updated by Andreas Kienast over 3 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.

Actions

Also available in: Atom PDF