I have a class with a private data store, in a custom format. I have made the data store private, so that people will work with the API and not directly mess with the underlying structure.
I want to implement a merge method, that will allow one instance of my class to merge into another. To make this performant, the merge function needs access to both instances’ data stores.
class MyClass() {
#myDataStore; // custom data structure that i don't want people messing with. (private)
...
mergeDataStores(instance2) {
const dataToMerge = instance2.#myDataStore; // !IMPORTANT! - this what I want to be able to do
... // perform the actions needed to merge the two.
}
...
}
const instance1 = new MyClass();
const instance2 = new MyClass();
... // various actions that load data into instance1 and instance2
instance1.merge(instance2);
is there any way I can accomplish this without exposing my data store?
Solutions that I don’t know how to implement, if they are even possible
- Is it possible to have an access modifier (aka another option for what other languages would call
public
,private
orprotected
) that means “this value can only be accessed by an instance of the same class”? - In a method, is it possible to check the instance of the class that invoked the method? That would let me create a getter that checks
if (!(invokingContext instanceof MyClass)) throw new Error("Access denied!");
Am I missing another option?