In JavaScript (ES5+), I\'m trying to achieve the following scenario:
I've been doing this lately:
// File-scope tag to keep the setters private.
class PrivateTag {}
const prv = new PrivateTag();
// Convenience helper to set the size field of a Foo instance.
function setSize(foo, size)
{
Object.getOwnPropertyDiscriptor(foo, 'size').set(size, prv);
}
export default class Foo
{
constructor()
{
let m_size = 0;
Object.defineProperty(
this, 'size',
{
enumerable: true,
get: () => { return m_size; },
set: (newSize, tag = undefined) =>
{
// Ignore non-private calls to the setter.
if (tag instanceof PrivateTag)
{
m_size = newSize;
}
}
});
}
someFunc()
{
// Do some work that changes the size to 1234...
setSize(this, 1234);
}
}
I think that covers all of the OP's points. I haven't done any performance profiling. For my use cases, correctness is more important.
Thoughts?