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 ?