这是我的简化示例。
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中实现这一目标?
答案 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);
}
}