TypeScript中支持的访问修饰符有哪些?
在 TypeScript 中,访问修饰符主要有三种:public、private 和 protected。这些修饰符可以用来设置类成员(包括属性和方法)的可见性。
- public:这是默认的访问修饰符,如果未明确指定访问修饰符,则默认为 public。public 成员在类的内部和外部都是可见的。
class Animal {
public name: string;
public constructor(name: string) {
this.name = name;
}
public speak() {
console.log(`${this.name} makes a noise.`);
}
}
- private:private 成员只能在声明它的类的内部访问。在类的外部试图访问 private 成员会导致编译错误。
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`); // 可以访问,因为在类内部
}
}
let a = new Animal("Fox");
console.log(a.name); // 编译错误,因为 name 是 private 的
- protected:protected 成员在声明它的类及其派生类中都是可见的,但在类的外部是不可见的。这允许派生类访问和修改基类的 protected 成员,同时防止非派生类进行访问。
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`); // 可以访问,因为在类内部
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks.`); // 可以访问,因为 Dog 是 Animal 的派生类
}
}
let d = new Dog("Buddy");
d.bark(); // 输出 "Buddy barks."
console.log(d.name); // 编译错误,因为 name 是 protected 的,只能在类及其派生类内部访问
浙公网安备 33010602011771号