面试题答案
一键面试在TypeScript中,类的访问修饰符有public
(公共的)、private
(私有的)和protected
(受保护的)。
public
修饰符
public
是默认的访问修饰符。使用public
修饰的属性或方法,可以在类的内部、类的实例以及子类中访问。
class Animal {
public name: string;
public constructor(name: string) {
this.name = name;
}
public sayHello(): void {
console.log(`Hello, I'm ${this.name}`);
}
}
let dog = new Animal('Buddy');
dog.sayHello(); // 输出: Hello, I'm Buddy
private
修饰符
使用private
修饰的属性或方法,只能在类的内部访问,类的实例和子类都无法访问。
class Secret {
private message: string;
constructor(message: string) {
this.message = message;
}
private showSecret(): void {
console.log(`The secret is: ${this.message}`);
}
public revealSecret(): void {
this.showSecret();
}
}
let secret = new Secret('Some confidential data');
// secret.showSecret(); // 报错: 'showSecret' 是私有的,只能在类 'Secret' 内部访问。
secret.revealSecret(); // 输出: The secret is: Some confidential data
protected
修饰符
使用protected
修饰的属性或方法,能在类的内部以及子类中访问,但不能通过类的实例访问。
class Shape {
protected color: string;
constructor(color: string) {
this.color = color;
}
protected describe(): void {
console.log(`This shape is ${this.color}`);
}
}
class Circle extends Shape {
constructor(color: string) {
super(color);
}
public draw(): void {
this.describe();
console.log('It is a circle.');
}
}
let circle = new Circle('red');
// circle.describe(); // 报错: 'describe' 是受保护的,只能在类 'Shape' 及其子类中访问。
circle.draw();
// 输出: This shape is red
// It is a circle.
区别总结:
public
:完全公开,随处可访问。private
:仅类内部可访问,实例和子类都不行。protected
:类内部和子类可访问,实例不可访问。