1

Considering the following "class" :

function Test()
{
    var data = new Uint8Array(232);
}

I would like to add the following accessor to the data attribute :

Object.defineProperty(Test.prototype, "data",
{
    get: function()
    {
        // calculate other things related to data
        return data;
    }
});

I encountered the following problems :

  • Defining the property inside the "class" scope works but makes each instances to redefine the property which is bad. Edit: this is where the relevancy of this question stops.
  • Defining the property outside obviously don't work since data is made private by closure.

So I tried to make the attributes public :

function Test2()
{
    this._data = new Uint8Array(232);
}

Object.defineProperty(Test2.prototype, "data",
{
    get: function()
    {
        // calculate other things related to data
        return this._data;
    },
    // Avoid "TypeError: setting a property that has only a getter"
    set: function(nv)
    {
        this._data = nv;
    }
});

Edit: I now use "_data" (instead of "data") as my private attribute to avoid a recursion problem with the "data" property. This pattern seems to work.

But is it a good and efficient pattern ? Is there a pattern that allow use of pseudo-private variables with properties ?

Community
  • 1
  • 1
Liios
  • 93
  • 8
  • 1
    Do you really need to name property on the object prototype and object itself by the same name? it's causing your error – Olena Horal Oct 05 '16 at 15:15
  • You are right. I guess I will go for the "_data" notation then. – Liios Oct 05 '16 at 15:56
  • It's an interesting question - do not close it until you get a good explanation why this happens – Olena Horal Oct 05 '16 at 16:03
  • If you already made `.data` a public property, you don't need an extra setter at all. – Bergi Oct 05 '16 at 16:03
  • @Bergi: yes I do. I don't want data to be accessed unless a certain process (a checksum calculation) is done before. – Liios Oct 05 '16 at 16:09
  • @BasileCopin, so what is your question now after your edit? – Max Koretskyi Oct 06 '16 at 09:13
  • @Maximus, my question ("How to use “private” attributes with properties in a class?") remain the same. The recursion problem was related to a workaround. I'm willing to use this workaround but only if this is the best solution. – Liios Oct 06 '16 at 12:33
  • "*Is there a pattern that allow use of pseudo-private variables with properties?*" - isn't that exactly what you're already doing with `._data`? – Bergi Oct 06 '16 at 12:34
  • Well as far as I know it's only private by convention that way. But I suppose it's good enough. – Liios Oct 07 '16 at 08:15

0 Answers0