简体   繁体   中英

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');
  }

}

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.

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