TypeScript继承、重写
要继承,那首先得有被继承的对象,当一回女娲,咱们造一个可以被继承的类:
class Parent{
private age:number; //私有变量,比如年龄。
protected wealth:string; //受保护的变量,也就是子类能够访问并使用,比如财富。
public name:string; //公开变量,所有个体都能访问,比如名字。
constructor(age=50,name="JoJo"){ //构造函数
this.age = age;
this.name = name;
this.wealth = this.age * 0.3 * 100000;
}
protected StandWake(){
console.log(this.name + " Wake a Stand is Purple of the Hermit!");
}
public BeingAttacked(attValue){
if(attValue > 0.7){
this.StandWake();
}
}
}
父类已经创建好了,那么接下来就是继承他,
class Child extends Parent{
public:string stantName;
//可以不创建构造函数,这样的话子类的构造延用父类,但是为了区分还是写一下
//注意:子类构造函数内第一句代码必须是super();
constructor(name,age=16,standName){
super(age,name);
this.standName = standName;
}
//重写函数
protected StandWake(){
console.log(this.name + " Wake a Stand is " + this.standName + "!");
}
}
ok,到此,继承和重写就已经完成了,我们来使用以下:
var josda:Parent = new Parent();
josda.name = "Joseph Josda";
josda.BeingAttacked(1);
console.log(josda.wealth);
var jotaro:Child = new Child("Jotaro Kujo",18,"Platinum Star");
jotaro.BeingAttacked(1);
console.log(jotaro.wealth);
哟西,逐渐jo化。