Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Andrew Khassapov Avatar asked Jun 26 '26 18:06

Andrew Khassapov


1 Answers

+++ 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; }
like image 191
Peter Seliger Avatar answered Jun 28 '26 08:06

Peter Seliger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!