How does variable declaration differ between the `class` and `constructor`?

前端 未结 3 639
面向向阳花
面向向阳花 2020-12-16 15:56

I have seen an example, and I am trying to reproduce it. The name and age are declared inside the class and services ( In

3条回答
  •  庸人自扰
    2020-12-16 16:35

    As the variables are defined, they are members of the Component1 class and any instance of the Component1 class has a name and an age public members of respectively string and number types.

    After the TypeScript is transpiled, there is no difference whether you declare them in the constructor, or as members. Before it's transpiled however, you have access to these members from instances of this class. This allows you to see errors while you're developing, like for example trying to set the age of a Component1 to something different from a number.

    var x = new Component1(a, b);
    x.age = "a"; // IDE/editor shows you have a problem here.
    

    The difference comes when you define a class member to be private. Then there is difference after the transpilation.

    Here's some docs on TS classes.

提交回复
热议问题