I have a JavaScript ES6 class in a library that uses some private base values to compute another value.
Abstracted and simplified the situation is something like this:
class Example {
#apples;
#oranges;
#cherries;
constructor() {
this.#apples = 22;
this.#oranges = 38;
this.#cherries = 12;
}
get numOfFruits() {
return this.#apples + this.#oranges + this.#cherries;
}
}
Now I want to add a function to Example to compute a new value e.g. something like:
Example.prototype.getNumOfApplesAndOranges = function() {
return this.#apples + this.#oranges;
};
I get that you are not supposed to access private variables outside their declaring class but I thought that by adding a method to the class the access happens within the class.
However this does not work and errors with Uncaught SyntaxError: reference to undeclared private field or method #apples
. Is there any way to make this work?
I already tried with eval
, Proxy
and Object.setPrototypeOf
but none of these helped.
class
block.class
declaration. "Abstracted and simplified" - if you could share the actual code, we might be able to provide a workaround.