角字段初始化与构造函数初始化? [英] Angular field initialization vs constructor initialization?

查看:143
本文介绍了角字段初始化与构造函数初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否需要使用角度分量的构造函数来初始化字段?许多角度教程都可以做到:

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

counter: number;

constructor() {
    this.counter = 1;
}

而不只是counter: number = 1.

推荐答案

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

Both are correct programming wise,

在构造函数中初始化

在构造函数中进行初始化是一种好习惯,这是声明+初始化的代码分离.

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.


在构造函数外部初始化

使用构造函数初始化的一个问题是,还有更多代码需要 如果您有很多变量要使用,请在这种情况下写 应该使用直接counter: number = 1,在这种情况下,您可以检查 声明+初始化在单行中,但在上述情况下,您 必须经历2步声明+初始化

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中选择一个进行初始化时,这确实很重要.要么只是编码风格

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

这篇关于角字段初始化与构造函数初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆