如何在TypeScript中声明私有抽象方法?

Zur*_*b-D 8 javascript 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())
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用.怎么解决?

Fen*_*ton 12

快点,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())
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望该方法是真正的私有,请不要在基类上声明它.

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())
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 那么如何才能强制孩子们的班级遵循同样的方法来实施呢? (2认同)