In JavaScript (ES5+), I'm trying to achieve the following scenario:
- An object (of which there will be many separate instances) each with a read-only property
.size
that can be read from the outside via direct property read, but cannot be set from the outside. - The
.size
property must be maintained/updated from some methods which are on the prototype (and should stay on the prototype). - My API is already defined by a specification so I can't modify that (I'm working on a polyfill for an already-defined ES6 object).
- I'm mostly trying to prevent people from shooting themselves in the foot accidentally and don't really have to have bulletproof read-only-ness (though the more bullet-proof it is, the better), so I am willing to compromise some on side door access to the property as long as directly setting
obj.size = 3;
isn't allowed.
I'm aware that I could use a private variable declared in the constructor and set up a getter to read it, but I would have to move the methods that need to maintain that variable off the prototype and declare them inside the constructor also (so they have access to the closure containing the variable). For this particular circumstance, I'd rather not take my methods off the prototype so I'm searching for what the other options might be.
What other ideas might there be (even if there are some compromises to it)?
configurable
and reconfigure them each time you want to change them, but that’s not much better than having a property called_size
. – Antonio