成员修饰符
一些面向对象编程语言(Java, C++)中都有成员修饰符特性,TypeScript 也引入成员修饰符。
成员修饰符有三个:
- public (默认) 公开的
- protected 受保护的
- private 私有的
这些修饰符实现了对象成员的访问控制
自身类 | 子类 | 类外部 | |
---|---|---|---|
public | √ | √ | √ |
protected | √ | √ | X |
private | √ | X | X |
//继承
class Father {
public name: string;
protected age: number;
private salary: number;
constructor(name: string, age: number, salary: number){
this.name = name;
this.age = age;
this.salary = salary;
}
info(){
console.log(this.name);
console.log(this.age);
console.log(this.salary);
}
}
class Son extends Father{
constructor(name: string, age: number, salary: number){
super(name, age, salary);
}
checkSalary(){
console.log(this.name);
console.log(this.age);
}
}
let xue = new Son('xue', 26, 16000);
console.log(xue.name);