javascriptclassinheritanceprivateprotected

How to simulate protected variables in javascript classes?


What is the best way to simulate protected variables in javascript?

class Parent{

    #variable; // Private variable. This is not to be public.

    constructor(value)
    {
        this.#variable = value;
    }
}

class Child extends Parent{

    getNewVariable()
    {
        return (1 + this.#variable); // Uncaught SyntaxError: Private field '#variable' must be declared in an enclosing class
                                     // We want #variable to be accessible without making it public.
    }
}

Since javascript doesn't support protected variables yet,

What is the best option for accessing private variables from superclasses in extended classes?

I haven't been able to find much documentation on this, so any suggestions would be very helpful.


Solution

  • +++ late answer, but here we go ... +++

    A WeakMap based approach most probably covers what the OP is looking for ...

    const protectedStatesMap = new WeakMap;
    
    class Parent{
      constructor(foo) {
        protectedStatesMap.set(this, { foo });
      }
      getFoo() {
        return protectedStatesMap.get(this).foo;
      }
    }
    class Child extends Parent{
      constructor(foo, bar) {
        super(foo);
    
        Object.assign(protectedStatesMap.get(this), { bar })
      }
      getBar() {
        return protectedStatesMap.get(this).bar;
      }
    }
    const childA = new Child('foo', 'bar');
    const childB = new Child('baz', 'biz');
    
    console.log('childA.getFoo() ...', childA.getFoo());
    console.log('childA.getBar() ...', childA.getBar());
    
    console.log('childB.getFoo() ...', childB.getFoo());
    console.log('childB.getBar() ...', childB.getBar());
    .as-console-wrapper { min-height: 100%!important; top: 0; }