What is the purpose of the public access modifier for classes in Typescript?

前端 未结 3 398
南方客
南方客 2021-01-20 17:38

What is the purpose of the public access modifier for classes in Typescript?

What is the difference between

export class Thing {

  public doStuff(){         


        
相关标签:
3条回答
  • 2021-01-20 18:23

    Your sample code means exactly the same in TypeScript. When you don't put a modifier public, private or protected on your member definition then TypeScript will choose the default one which is public.

    That not make sense for Javascript because TypeScript transpiler will generate exactly the same code. But those modifiers will help you to encapsulate your class members and make them :

    • accessible outside of the class : public
    • only accessible in the class only : private
    • accessible in the class and the derived classes: protected

    Again the generated Javascript will not contain the modifiers. That means that if someone get your Javascript code it will access to the members even if you defined them as private. The modifiers are only helpful in TypeScript and help developers to not access some class members.

    0 讨论(0)
  • 2021-01-20 18:23

    It's just an explicit way to set the method to be public. By default all class methods / properties in TypeScript are of type public, but you can as well note this in your code for clarity.

    You can read more about it in the Handbook, here is an excerpt :

    Public by default

    In our examples, we’ve been able to freely access the members that we declared throughout our programs. If you’re familiar with classes in other languages, you may have noticed in the above examples we haven’t had to use the word public to accomplish this; for instance, C# requires that each member be explicitly labeled public to be visible. In TypeScript, each member is public by default.

    You may still mark a member public explicitly.

    0 讨论(0)
  • 2021-01-20 18:35

    Two reasons for using public, one subjective/style, the other objective:

    1. It's in-code documentation. Leaving off an access modifier could be taken as your having forgotten it. (This is the subjective/style reason.)

    2. If you want to use the shorthand initialization feature TypeScript adds to class constructors, you need the public to tell TypeScript to do that.

    Here's an example of #2:

    class Example {
        constructor(public name: string) {
    //              ^^^^^^---------------- This is what triggers the feature
        }
    }
    const e = new Example("Joe");
    console.log(e.name); // "Joe"
    

    (On the playground.)

    0 讨论(0)
提交回复
热议问题