Typescript: Difference between declaring class variables using private, public and nothing

前端 未结 1 852
盖世英雄少女心
盖世英雄少女心 2021-01-19 01:59

What\'s the difference between:

A.
class foo {
  bar: string;
}

B.
class foo {
  private bar: string;
}

C.
class foo {
  public bar: string;
}
相关标签:
1条回答
  • 2021-01-19 02:36

    bar: string is 100% equivalent to public bar: string. The default accessibility modifier is public.

    private is compile-time privacy only; there is no runtime enforcement of this and the emitted code is identical regardless of the access modifier. You'll see an error from TypeScript when trying to access the property from outside the class.

    You could also have said protected, which is like private except that derived classes may also access the member. Again, there's no difference in the emitted JavaScript here.

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