class 类
public:内部和外部都能访问到
private:只在类的内部可以访问
protected :只在当前类及子类内部可访问
class Person {
constructor(public name: string) { //构造函数中的参数如果加了前缀,就是this.xxx的简写
console.log(this.name) //构造函数中的内容会在创建对象时运行一次
};
public age?: number; //不加publiuc则默认是public
say(): void {
console.log(this.age?this.age:'no age')
};
}
let xiaoming :Person = new Person('xiaoming'); //--->xiaomming
xiaoming.say(); //---> no age
xiaoming.age = 10;
xiaoming.say(); //---> 10
extends 子类继承父类 super,在子类中访问父类
class Person {
public constructor(public name: string) {
console.log(this.name)
};
public age?: number;
public say(): void {
console.log(this.age?this.age:'no age')
};
}
class Worker extends Person{
constructor(public name:string,public age:number){
super(name); //运行Persoon的构造函数
super.say(); //运行say方法
this.Work(); //运行自己的私有方法
};
private Work():void{
console.log('code')
}
}
let xiaohong:Worker = new Worker('xiaohong',16) //---》 xiaohong / 16 / code