I'm creating a class in Javascript (Note: I am actually using Google Apps Script, but this should be a generic Javascript question).
Inside of the class is an array of objects - specifically an array of another class I have declared. I want to ensure that the array contains ONLY instances of my class.
Here is the basics of what I have:
class subClassA {
constructor(name) {
this.name = name;
this.mode = new Modes; //Creates instance of another custom class (not shown here)
Object.seal(this); //Prevents adding new or removing any extensions to object without editing this class
}
}
class subClassACollection {
constructor() {
this.array = [];
Object.seal(this); //Prevents adding new or removing any extensions to object without editing this class
return this.array; //Returns the array when used in formulas rather than the object
}
}
class class1 {
constructor(name) {
this.name = name;
this.mode = new Modes;
this.collection = new subClassACollection;
Object.seal(this); //Prevents adding new or removing any extensions to object without editing this class
}
addtoCollection(sca) {
if (sca instanceof subClassA) {
this.collection.push(subClassA);
} else if (typeof sca == "string") {
this.collection.push(new subClassA(sca));
} else {
//Incomplete, should generate an error or message to user here
}
}
}
What I want to do, is force the use of the '.addtoCollection' method to add another subClassA
object to the collection/array to ensure that only instances of subClassA
objects can be added and nothing else.
I was hoping by making the array it's own class, that would bury it a layer deep and not make it accessible. I thought using the return
statement above would make it return the array for reading the values without making it modifiable from the outside. To my surprise, I can simply make an assignment like class1.collection = 'hi'
which adds a string or any other variable or object type into the array/collection. I don't want to be able to do that! I want to ensure that the only thing that can be added to that array is of type subClassA
- how do I accomplish that with a class?
NOTE: I have seen how to do this with a function - but I want to do this entirely within the class if possible, so these properties are inherent to the variables I'm creating, rather than assigning a function output to another variable. If it can be done with a method inside the class, that is fine - but I don't know how to keep the variables inside the method "alive" for the next call (similar to a static method in C).