I know I can create a private constant by putting it into an IIFE's closure:
let testObj = (function() {
const myConst = 'test value';
return {
showPrivateConst() {
return myConst;
}
}
})();
console.log(testObj.showPrivateConst()); // test value
But I'm looking for the best way to do this using class syntax and the # private indicator. So far, the best I've come up with is this:
class Test {
get #myConst() {
return 'test value';
}
showPrivateConst() {
return this.#myConst;
}
}
let testObj = new Test();
console.log(testObj.showPrivateConst()); // test value
This seems kind of baroque. Is this the way to do it, setting up a read-only private property to get a private constant, or is there a more idiomatic way to do it?
Edit: I've been getting some feedback about static properties being the way to do this. I've looked at static properties as well, and they pretty much give me the same question. I can't make a private static variable a constant, so it looks like I have to make it a readonly property using a getter method. Here's the example using a static property:
class Test {
static get #myConst() {
return 'test value';
}
showPrivateConst() {
return Test.#myConst;
}
}
let test = new Test();
console.log(test.showPrivateConst()); // test value
So, this gives rise to pretty much the same question. It seems kind of baroque, and I'm wondering if there's a more idiomatic way to do it.