[英]How to declare private abstract method in 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())
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.