Angular field initialization vs constructor initialization?

那年仲夏 提交于 2019-12-13 07:54:15

问题


Do fields need to be initialized using the constructor for angular components? A lot of angular tutorials do:

counter: number;

constructor() {
    this.counter = 1;
}

Instead of just counter: number = 1.


回答1:


Both are correct programming wise,

Initialized within the constructor

It would be good practice to initialized within the constructor , it's kind of code separation of declaration + initialization .

That will increase your code readability and you will be sure that all values initialized within the constructor only. and because in the constructor is when the object is created, and it is when the variable should initialized.


Initialized outside the constructor

One issue with initialized using the constructor is , more code to write , when you have alot variable to work with , in that case you should use direct counter: number = 1 , In this case you can check declaration + initialization in single line , but in above case you have to go through 2 steps declaration + initialization

It really matters when you choose initialisation within one of the life cycle hook (E.g. NgOnInit / NgAfterViewInit) vs the constructor. Either it's just a coding style



来源:https://stackoverflow.com/questions/48860024/angular-field-initialization-vs-constructor-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!