推荐答案
在 TypeScript 中,类的访问修饰符用于控制类成员的可见性和可访问性。TypeScript 提供了三种主要的访问修饰符:public、private 和 protected。
- public: 默认的访问修饰符。
public成员可以在类的内部、外部以及子类中访问。 - private:
private成员只能在类的内部访问,外部和子类都无法访问。 - protected:
protected成员可以在类的内部和子类中访问,但不能在类的外部访问。
本题详细解读
public
public 是 TypeScript 中默认的访问修饰符。如果你没有显式地指定访问修饰符,那么类成员默认是 public 的。public 成员可以在类的内部、外部以及子类中访问。
// www.javascriptcn.com code example
class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person("Alice");
console.log(person.name); // 输出: Aliceprivate
private 修饰符限制了成员的访问范围,只能在类的内部访问。外部和子类都无法访问 private 成员。
// www.javascriptcn.com code example
class Person {
private age: number;
constructor(age: number) {
this.age = age;
}
public getAge(): number {
return this.age;
}
}
const person = new Person(30);
console.log(person.getAge()); // 输出: 30
// console.log(person.age); // 错误: 属性“age”为私有属性,只能在类“Person”中访问protected
protected 修饰符允许成员在类的内部和子类中访问,但不能在类的外部访问。
// www.javascriptcn.com code example
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getDetails(): string {
return `Name: ${this.name}, Department: ${this.department}`;
}
}
const employee = new Employee("Bob", "HR");
console.log(employee.getDetails()); // 输出: Name: Bob, Department: HR
// console.log(employee.name); // 错误: 属性“name”受保护,只能在类“Person”及其子类中访问通过这些访问修饰符,TypeScript 提供了对类成员的访问控制,帮助开发者更好地封装和管理代码。