1

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?

2 Answers 2

1

How can the instances be garbage-collected if instanceData will hold them?

They can't. That's why you should not use this approach. Instead, use a WeakMap.

Moreover, the spec enforces searches in a WeakMap to be sublinear on average. With an array it would be linear.

let instanceData = new WeakMap();
class AClass {
  constructor () {
    // Write
    instanceData.set(this, {
      'privateProperty': true
    });
    // Read
    console.log(instanceData.get(this));
  }
}
new AClass();

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use private properties, Symbol may help you.

const SOME_PROPERTY = Symbol('someProperty');
class AClass {
  constructor(){
      this[SOME_PROPERTY] = true;
  }
  get someProperty(){
      return this[SOME_PROPERTY];
  }
}
var aObj = new AClass();
console.log(aObj.someProperty);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.