📅  最后修改于: 2023-12-03 14:48:05.826000             🧑  作者: Mango
在编写 TypeScript 代码时,我们需要使用访问修饰符来控制类的成员的可访问范围。TypeScript 提供了 3 种访问修饰符:public、private 和 protected。
public 是默认的访问修饰符,如果没有显式指定访问修饰符,那么成员的访问修饰符就是 public。
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getInfo(): string {
return `Name: ${this.name}, Age: ${this.age}`;
}
}
const person = new Person("Tom", 20);
console.log(person.name); // Tom
console.log(person.age); // 20
console.log(person.getInfo()); // Name: Tom, Age: 20
通过上面的代码示例可以看出,类的成员如果没有指定访问修饰符,那么就是 public 的。在类的外部可以访问类的成员,也可以调用类的方法。
private 修饰符可以用来限制在类的外部不能访问类的成员。
class Person {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getInfo(): string {
return `Name: ${this.name}, Age: ${this.age}`;
}
}
const person = new Person("Tom", 20);
console.log(person.name); // Property 'name' is private and only accessible within class 'Person'.
console.log(person.age); // Property 'age' is private and only accessible within class 'Person'.
console.log(person.getInfo()); // Name: Tom, Age: 20
通过上面的代码示例可以看出,当类的成员被 private 修饰符修饰时,外部不能访问这些成员。
protected 修饰符表示这个成员可以被子类访问,但是在类的外部是不允许访问的。
class Person {
protected name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
constructor(name: string, age: number) {
super(name, age);
}
getInfo(): string {
return `Name: ${this.name}, Age: ${this.age}`;
}
}
const student = new Student("Tom", 20);
console.log(student.name); // Property 'name' is protected and only accessible within class 'Person' and its subclasses.
console.log(student.age); // Property 'age' is protected and only accessible within class 'Person' and its subclasses.
console.log(student.getInfo()); // Name: Tom, Age: 20
通过上面的代码示例可以看出,当类的成员被 protected 修饰符修饰时,子类可以访问这些成员,外部不能访问这些成员。
总结: