Understanding “public” / “private” in typescript class

前端 未结 3 878
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 15:22

In the below type script code , irrespective of whether name is \"public\" or \"private\" , java script code that is generated is same.

So my question is, how to decide

3条回答
  •  伪装坚强ぢ
    2021-02-05 15:29

    The public, private, protected access modifiers, as you have discovered, don't actually affect the final outputted code. What they do affect is the type checking at compile time.

    What do they actually do?

    As their names suggest, the public and private modifiers limit what can access the class member. Their is also a third modifier in the clan, protected.

    The private modifier only allows a class member (variable or method) to be accessed within that class.

    The protected modifier allows everything the private modifier does, and also allows other classes that extend that class to use it.

    Finally, the public modifier makes it so anything can access the class also has access to the public class property.

    For a more in-depth explanation and examples, take a look at the official TypeScript Handbook's explanation.

    If it all compiles the same, why should I use the modifiers?!

    Using the modifiers will enable the compiler to make sure that your code isn't using things that it shouldn't be using. This is the same reasoning behind using types in the first place, it makes it harder to make mistakes that shouldn't be able to be made in the first place! As an added bonus, if your text editor has TypeScript support, it will also use the access modifiers when showing you autocomplete values for variables and methods.

提交回复
热议问题