如何在 TypeScript 中正确定义私有抽象方法?
这是一个简单的代码:
abstract class Fruit {
name: string;
constructor (name: string) {
this.name = name
}
abstract private hiFrase (): string;
}
class Apple extends Fruit {
isCitrus: boolean;
constructor(name: string, isCitrus: boolean) {
super(name);
this.isCitrus = isCitrus;
}
private hiFrase(): string {
return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (isCitrus ? "" : " not ") + "citrus";
}
public sayHi() {
alert(this.hiFrase())
}
}
这段代码不起作用。如何修复它?
快到一边去,isCitrus
应该this.isCitrus
。继续重头戏……
抽象方法must对子类可见,因为您需要子类实现该方法。
abstract class Fruit {
name: string;
constructor (name: string) {
this.name = name
}
protected abstract hiFrase(): string;
}
class Apple extends Fruit {
isCitrus: boolean;
constructor(name: string, isCitrus: boolean) {
super(name);
this.isCitrus = isCitrus;
}
protected hiFrase(): string {
return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus";
}
public sayHi() {
alert(this.hiFrase())
}
}
如果您希望该方法真正私有,请不要在基类上声明它。
abstract class Fruit {
name: string;
constructor (name: string) {
this.name = name
}
}
class Apple extends Fruit {
isCitrus: boolean;
constructor(name: string, isCitrus: boolean) {
super(name);
this.isCitrus = isCitrus;
}
private hiFrase(): string {
return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus";
}
public sayHi() {
alert(this.hiFrase())
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)