I've a case where I need to protect properties stored in instance of a class. I want that only my class have access to get/set certain properties of an instance – so my solution is to have a factory function for this class, and inside this factory I store an array which store data of each instance.
So I'd have this, for example:
let instanceData = [];
class AClass {
constructor () {
instanceData.push([this, {
'privateProperty': true
}]);
}
}
The reason why instanceData is an array is because the key of every property casts into string, so I put arrays inside there, containing the object of that instance as first element and containing the data of that instance as second element.
When I want to access the data of an instance I just need to search an array that has array[0] === instance inside instanceData.
My example would work fine, but what about garbage-collector? How can the instances be garbage-collected if instanceData will hold them?