user1275105
user1275105

Reputation: 2753

What the difference between setting value of variables within the constructor or outside it

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.

Upvotes: 1

Views: 119

Answers (1)

Enryu
Enryu

Reputation: 1424

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.

Upvotes: 3

Related Questions