使派生类方法对外部私有,但在es6中可以在baseclass中访问

时间:2016-12-28 01:03:00

标签: javascript ecmascript-6

这是我的简化示例。

class BasePerson{
    constructor(name){
        this.name = name || "noname";   
    }

    shout(){
        var shoutMessage = this._talk() + "!!!!!";
        console.log(shoutMessage);
    }
}

class HappyPerson extends BasePerson{

    constructor(name){
        super(name);
        this.message = "LA LA LA LA LA";
    }   

    _talk(){
        return this.message;
    }
}

var person1 = new HappyPerson();
person1.shout(); //LA LA LA LA LA!!!!!
person1._talk(); //returns LA LA LA LA LA but I want _talk to be undefined

我想要实现的是,在获取HappyPerson的实例时将 _talk 方法设为私有,但只能在BasePerson类中访问它。如何在es6中实现这一目标?

1 个答案:

答案 0 :(得分:0)

您似乎尝试实现一种抽象方法(因为您希望父级在子级上调用它的实现,即使您希望从子类中隐藏您的方法,这很奇怪)。如果这正是您想要的,也许您可​​以将_talk函数作为回调传递给shout parent的函数。不完全相同的解决方案,但它是干净的并保持私密,如下所示:

class BasePerson{
    constructor(name){
        this.name = name || "noname";   
    }

    shout(talkFn){
        var shoutMessage = talkFn() + "!!!!!";
        console.log(shoutMessage);
    }
}

class HappyPerson extends BasePerson{

    constructor(name){
        super(name);
        this.message = "LA LA LA LA LA";
    }   

    shout(){
        super.shout(()=>this.message);
    }
}