如何在TypeScript中声明私有的抽象方法?
问题描述:
如何在TypeScript中正确定义私有抽象方法?如何在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
。主显示...
抽象方法必须对于子类是可见的,因为您要求子类实现该方法。
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())
}
}
http://stackoverflow.com/questions/13333489/declaring-abstract-method-in-typescript –
'private'的可能的复制==只有非常同一类的访问。 'abstract' ==没有在这个类中实现,而是在一些继承类中实现。这里有一些定义冲突。 – deceze
你想'受保护的抽象'而不是'私人抽象'。 – series0ne