Mohamed Sahir
Mohamed Sahir

Reputation: 2543

JavaScript - getter function vs constructor - which is executed first?

I need to know which is executed first in the component and execution order.

Get is called before constructor or Constructor gets called first. I am unable to put console in Get accessor.

export class AppComponent implements OnChanges {
  title = 'app';

  constructor() {
    console.log('constructor called on App Component');
  }

  ngOnChanges() {
    console.log(' onChanges called on App Component');
  }

  clicked() {
    console.log('red');
  }

  get name(): string {
    return 'sahir';
    console.log('called get method');
  }

}

Upvotes: 0

Views: 408

Answers (1)

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

The constructor will always be called first. You need an instance of the class in order to access a property.

Also, the console.log you put on the getter will never run since it is after a return statement.

Upvotes: 2

Related Questions