OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Get value of private variable in extension method ES6 class in JavaScript

  • Thread starter Thread starter tesmo
  • Start date Start date
T

tesmo

Guest
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:

Code:
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:

Code:
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.

<p>I have a JavaScript ES6 class in a library that uses some private base values to compute another value.</p>
<p>Abstracted and simplified the situation is something like this:</p>
<pre class="lang-js prettyprint-override"><code>class Example {
#apples;
#oranges;
#cherries;

constructor() {
this.#apples = 22;
this.#oranges = 38;
this.#cherries = 12;
}

get numOfFruits() {
return this.#apples + this.#oranges + this.#cherries;
}
}
</code></pre>
<p>Now I want to add a function to Example to compute a new value e.g. something like:</p>
<pre class="lang-js prettyprint-override"><code>Example.prototype.getNumOfApplesAndOranges = function() {
return this.#apples + this.#oranges;
};
</code></pre>
<p>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.</p>
<p>However this does not work and errors with <code>Uncaught SyntaxError: reference to undeclared private field or method #apples</code>. Is there any way to make this work?</p>
<p>I already tried with <code>eval</code>, <code>Proxy</code> and <code>Object.setPrototypeOf</code> but none of these helped.</p>
 
Top