简体   繁体   中英

Best practice class member initialization

When I have a class like:

import {Subject} from "rxjs";

export class MyClass {
  protected subject: Subject<string>;
}

is it better practice in TypeScript to initialize the member subject in the constructor like:

export class MyClass {
  protected subject: Subject<string>;

  constructor() {
    this.subject = new Subject<string>();
  }
}

or inline in the class body like:

export class MyClass {
  protected subject: Subject<string> = new Subject<string>();
}

NOTE

Inline initialization obviously only works with imported classes like Subject in this case, not with injected classes, which would only be present in the constructor.

EDIT

The Angular Style Guide does not contain this part.

It does not matter. Both code snippets will be transpiled exactly to the same code which is

export class MyClass {
    constructor() {
        this.subject = new Subject();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM