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

What are access modifiers in TypeScript classes?

1个答案

1

In TypeScript, the main access modifiers for classes are public, private, and protected. These modifiers define the access level for class members (properties and methods).

  1. public (Public): This is the default access level. Members marked as public can be accessed anywhere, both inside and outside the class. This means that any place where an instance of the class is created can access and modify these members.

Example:

typescript
class Animal { public name: string; constructor(name: string) { this.name = name; } public display(): void { console.log(this.name); } } let dog = new Animal("Buddy"); dog.display(); // Output: Buddy console.log(dog.name); // Output: Buddy
  1. private (Private): Members marked as private can only be accessed within the class. This means these members cannot be directly accessed outside the class or in any subclass that inherits from it.

Example:

typescript
class Animal { private name: string; constructor(name: string) { this.name = name; } display(): void { console.log(this.name); } } let cat = new Animal("Whiskers"); cat.display(); // Output: Whiskers // console.log(cat.name); // Error: Property 'name' is private and only accessible within class 'Animal'.
  1. protected (Protected): Members marked as protected can be accessed within the class and in any subclass that inherits from it. However, they cannot be directly accessed outside class instances.

Example:

typescript
class Animal { protected name: string; constructor(name: string) { this.name = name; } } class Cat extends Animal { constructor(name: string) { super(name); } display(): void { console.log(this.name); } } let cat = new Cat("Paws"); cat.display(); // Output: Paws // console.log(cat.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.

These access modifiers help implement encapsulation and hide internal implementation details, contributing to clean and secure code.

2024年8月2日 13:49 回复

你的答案