2

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 ?

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105
  • There are only workarounds, such as using a `Map` or `WeakMap` that is accessible by `BasePerson` and `HappyPerson` but nowhere else. You can use the map to associate data with an instance. – Felix Kling Dec 28 '16 at 01:05
  • This is wrong. The methods of a class shouldn't require the object to be an instance of a subclass. `shout` should be a `HappyPerson` method, and then your question is a dupe of [accessing private member variables from prototype-defined functions](http://stackoverflow.com/q/436120/1529630) – Oriol Dec 28 '16 at 01:08
  • mmm I think the inheritance is backwards ... IMO, `_talk` should be in the `BasePerson` class and `shout` on the `HappyPerson` class. as @Oriol mentioned... the base class should not use any methods from their child classes. If you change the methods like that, do you get the desired result? – David Espino Dec 28 '16 at 01:34

1 Answers1

0

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);
    }
}
David Rissato Cruz
  • 3,347
  • 2
  • 17
  • 17