Angular 字段初始化与构造函数初始化?

Angular field initialization vs constructor initialization?

是否需要使用 angular 组件的构造函数来初始化字段?很多 angular 教程都这样做:

counter: number;

constructor() {
    this.counter = 1;
}

而不只是 counter: number = 1.

两者都是正确的编程方式,

在构造函数中初始化

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.


在构造函数外初始化

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

在生命周期钩子之一(例如 NgOnInit / NgAfterViewInit)和 constructor 中选择初始化真的很重要。要么只是一种编码风格