1

What's the difference between this:

export class List {
  categories: any[];
  constructor() {
    this.categories = ['First Class', 'Second Class', 'Economy'];
  }
}

And this:

export class List {
  categories: any[] = ['First Class', 'Second Class', 'Economy'];
  constructor() {
  }
}

Both compile to the same Javascript code. Considering, in this particular example, the class is never going to be instantiated with passed in values, am I OK sticking with the second option of setting the values outside the constructor function?

This is in the context of Angular2 class components using typescript.

user1275105
  • 2,643
  • 5
  • 31
  • 45

1 Answers1

3

If you are not going to ever instantiate the class with values passed in by the constructor, functionally each implementation of the class will work essentially the same, though it is probably better coding practice to use the second implementation of the class where the array is set to values outside of the constructor.

Enryu
  • 1,406
  • 1
  • 14
  • 26
  • To expand upon this, when the array is set outside of the constructor it will hold these values regardless of whether the class is instantiated or not. If you decide to use the class without instantiating it (for example through a static method), then the array will not contain any values if the values are set in the constructor. If you set the values outside of the constructor as class level variables then the array will contain those values regardless of whether the class is instantiated or not, which is why I said it would be the better way to implement this class. – Enryu Jun 12 '16 at 13:07
  • best answer is here http://stackoverflow.com/questions/36147890/angular2-what-is-different-between-the-variable-declaring-in-the-class-and – stackdave Dec 29 '16 at 11:37