typescript中,默认使用public,
当成员被标记为private时,它就不能在声明它的类的外部访问,比如:
class Afengge{
private name: string;
constructor(name: string) {
this.name = name;
}
}
let a = new Afengge('Cat').name; //错误,‘name’是私有的
而protected和private类似,但是,protected成员在派生类中可以访问
class Afengge{
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Xiaoqiaozi extends Afengge{
constructor() {
super('xiaoqiaozi');
}
getName() {
console.log(this.name) //此处的name就是Afengge类中的name
}
}
而构造函数也可以被标记为protected。这意味着这个类不能再包含它的类外被实例化,但是能被继承,也就是可以在派生类中被super执行。
lass Afengge{
protected name: string;
protected constructor(name: string) {
this.name = name;
}
}
//Xiaoqiaozi能够继承Afengge
class Xiaoqiaozi extends Afengge{
private food: string;
constructor(name: string, food: string) {
super(name);
this.food = food;
}
getFood() {
return `${this.name} love this ${this.food}`
}
}
let rhino = new Xiaoqiaozi('xu', 'daxigua');