类成员的修饰符
- public:公有属性,可以在类内部访问,可以在实例访问,可以在子类访问
- private:私有属性,外部不能访问,只在类内部访问
- protected:受保护的,自身和子类访问
-
static:静态,只能是类本身访问,不可在类内部访问,不可在子类访问,不可在实例访问
class A1 {
public x: number;
protected y: string;
private z: boolean;
static w: number = 100
constructor(x: number, y:string) {
this.x = x;
this.y = y;
this.z = true;
}
public test(): void {
// 访问
console.log('this.x ==>', this.x);
// 访问y
console.log('this.y ==>', this.y);
// 访问z
console.log('this.z ==>', this.z);
// 访问w
// console.log('this.w ==>',this.w);
}
}
class A2 extends A1{
public getData(): void{
console.log('A2 this.x ==>',this.x);
console.log('A2 this.y ==>', this.y);
// console.log('A2 this.z ==>',this.z);
}
}
let a1: A1 = new A1(2,'hello');
console.log('a1 ==>',a1);
a1.test();
// console.log('a1.y ==>',a1.y);
// console.log('a1.z ==>',a1.z);
let a2: A2 = new A2(8, 'world');
console.log('a2 ==>',a2);
a2.getData()
// console.log('a2.y ==>',a2.y);
// 访问A1类的静态属性w
console.log('A1.w ==>',A1.w);