TypeScript supports three main access modifiers used for class properties and methods to control their accessibility.
- public: If a member is marked as public, it can be accessed freely from anywhere. In TypeScript, if no access modifier is explicitly specified, it defaults to public. For example, a class method that can be directly accessed from outside is typically public.
typescriptclass Employee { public name: string; constructor(name: string) { this.name = name; } public greet() { console.log(`Hello, my name is ${this.name}`); } } let emp = new Employee("Alice"); emp.greet(); // Output: Hello, my name is Alice
- private: If a member is marked as private, it can only be accessed within the class where it is defined. Private members cannot be accessed outside the class.
typescriptclass Employee { private salary: number; constructor(salary: number) { this.salary = salary; } private displaySalary() { console.log(`My salary is ${this.salary}`); } } let emp = new Employee(50000); // emp.displaySalary(); // Error: displaySalary is private.
- protected: The protected modifier is similar to private, but it can also be accessed in derived classes. This makes protected suitable for defining members in a base class that should only be accessible to derived classes.
typescriptclass Employee { protected department: string; constructor(department: string) { this.department = department; } } class Manager extends Employee { constructor(department: string) { super(department); } public getDept() { console.log(`I manage the ${this.department} department.`); } } let mgr = new Manager("Sales"); mgr.getDept(); // Output: I manage the Sales department.
These access modifiers help us implement encapsulation and hide implementation details in large projects, making the code more modular and maintainable.
2024年11月29日 09:31 回复