Initializing variables inline during declaration vs in the constructor in Angular with TS

后端 未结 2 1360
长发绾君心
长发绾君心 2021-01-02 03:43

I have been working for a while with Angular but can\'t find a definitive recommendation on :

Initializing member variables inline vs in the constructor

相关标签:
2条回答
  • 2021-01-02 04:17

    It's a personal style preference.

    Initializing a property in the constructor allows you to leverage constructor parameters when you're initializing the property.

    Initializing a property inline is more concise, and keeps the default value of the property more in context with its declaration.

    TypeScript compiler just brings values initialized inline inside the constructor https://www.typescriptlang.org/play/

    0 讨论(0)
  • 2021-01-02 04:18

    There is no difference basically, its just the convenience. Only difference for using constructor initialization is you can pass the value dynamically and then assign to it.

    constructor(visible) {
        this.isVisible = visible;  // <-- vs initialization in the constructor
    }
    
    0 讨论(0)
提交回复
热议问题