简体   繁体   中英

Making derived class method private to outside but reachable at baseclass in es6

This is my simplified example.

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

What I want to achieve is, making _talk method private when taking an instance of a HappyPerson but it should be reachable only at BasePerson class. How to achieve this in es6 ?

It seems like you tried to implement a kind of abstract method (because you wanted the parent calling an implementation of it on the child, even though you wanted your method to be hidden from your child class, which is odd). If this is exactly what you wanted, maybe you could pass the _talk function as a callback to the shout parent's function. Not exactly the same solution, but it is clean and keep things private, like this:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM