乐闻世界logo
搜索文章和话题

Name the access modifiers supported in TypeScript.

1个答案

1

In TypeScript, three primary access modifiers are supported, each defining a distinct level of accessibility. These access modifiers are:

  1. public: This is the most commonly used modifier, indicating that members (such as class properties or methods) are publicly accessible. Public members can be freely accessed anywhere, including outside the class. By default, if no access modifier is specified, members are considered public.

Example:

typescript
class Animal { public name: string; constructor(name: string) { this.name = name; } public display(): void { console.log(`This animal's name is ${this.name}`); } } let dog = new Animal("Buddy"); dog.display(); // Works correctly
  1. private: The private modifier indicates that members are private and can only be accessed within the class where they are defined. Accessing private members from outside the class results in a compilation error.

Example:

typescript
class Animal { private name: string; constructor(name: string) { this.name = name; } private display(): void { console.log(this.name); } public show(): void { this.display(); // Calling private method internally } } let cat = new Animal("Whiskers"); // cat.display(); // Error: 'display' is private. cat.show(); // Works correctly, as it internally calls private method display
  1. protected: The protected modifier indicates that members are accessible within the class itself and its subclasses, but not directly from outside the class. This is particularly useful when restricting access while enabling class inheritance.

Example:

typescript
class Animal { protected name: string; constructor(name: string) { this.name = name; } protected display(): void { console.log(`Animal's name: ${this.name}`); } } class Dog extends Animal { constructor(name: string) { super(name); } public show(): void { this.display(); // Can access protected method } } let dog = new Dog("Buddy"); dog.show(); // Works correctly // dog.display(); // Error: 'display' is protected.

These access modifiers leverage the encapsulation feature of classes, enabling developers to appropriately use class members in the correct context while safeguarding data from inappropriate access or modification.

2024年11月29日 09:39 回复

你的答案