In TypeScript, access modifiers control the accessibility of class members, enabling encapsulation and protecting the state of objects. TypeScript supports three primary access modifiers:
- public: The public modifier is the default access level. Members marked as public can be accessed from anywhere without restrictions.
Example:
typescriptclass Animal { public name: string; constructor(name: string) { this.name = name; } public move(distance: number) { console.log(`${this.name} moved ${distance}m.`); } }
- private: The private modifier restricts access to within the class. Members marked as private cannot be accessed outside the class or by derived classes.
Example:
typescriptclass Animal { private name: string; constructor(name: string) { this.name = name; } private move(distance: number) { console.log(`${this.name} moved ${distance}m.`); } }
- protected: The protected modifier is similar to private but allows derived classes to access protected members.
Example:
typescriptclass Animal { protected name: string; constructor(name: string) { this.name = name; } protected move(distance: number) { console.log(`${this.name} moved ${distance}m.`); } } class Bird extends Animal { fly(distance: number) { console.log(`${this.name} flies ${distance}m.`); this.move(distance); } }
These access modifiers help define safer and more structured code by restricting unnecessary external access, thereby enhancing maintainability and stability. In practical applications, using these modifiers appropriately can significantly improve code quality.
2024年7月17日 22:39 回复