1. 拜访修饰符
用于设置类中变量和办法的拜访权限
public(默认): 私有,能够在任何中央被拜访
protected : 受爱护,只在以后类和其子类中被拜访(在类的内部无奈被拜访)
private : 公有,只在以后类中能够被拜访(在子类中或者类的内部都无奈被拜访)
class Person {
public name: string;
protected age: number;
private sex: string;
constructor(name: string, age: number, sex: string) {
this.name = name;
this.age = age;
this.sex = sex;
}
public show(): void {console.log(this.name + this.sex + this.age);
}
}
let alias = new Person("alias", 18, "女");
console.log(alias);
console.log(alias.name);
// 1. 被 protected 或者 private 润饰的变量或者属性,在类的内部无奈被拜访
// console.log(alias.age); // protected 权限限度,此属性不可被拜访
// console.log(alias.sex); // private 权限限度,此属性不可被拜访
alias.show();
class Student extends Person {
grade: string;
constructor(name: string, age: number, sex: string, grade: string) {super(name, age, sex);
this.grade = grade;
}
show(): void {
// 1. 在父类中被 private 润饰的变量或者属性,在子类中无奈被拜访
console.log(this.name + this.age /*+ this.sex */ + this.grade);
}
}
let xiaoming = new Student("小明同学", 12, "男", "五年级");
console.log(xiaoming);
// 2. 在父类中被 protected 或者 private 润饰的变量或者属性,在继承它的子类的内部也无奈被拜访
// console.log(xiaoming.age); // 父类 protected 权限限度,此属性不可被拜访
// console.log(xiaoming.sex); // 父类 private 权限限度,此属性不可被拜访
xiaoming.show();
罕用于爱护成员变量,裸露成员办法:
用 private 或 protected 爱护成员变量(不让它在内部被批改,只能通过 get,set 办法或者实例化时被批改),用 public 润饰成员办法(对外裸露)
2. 只读修饰符(readonly)
只能在变量初始化 或者 constructor 构造函数中给 readonly 润饰的属性赋值。只可读,不可批改。
class Student {
name: string;
readonly age: number;
readonly sex: string = "男"; // 赋值地位一
constructor(name: string, age: number) {
this.name = name;
this.age = age; // 赋值地位二,同时赋值:地位二会笼罩地位一
}
}
let alias = new Student("alias", 18);
alias.name = "小明";
// alias.age = 100; // 只读 阻止再次赋值
console.log(alias);