Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
How do I force using a method to assign class variables in Javascript?

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).

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In general JavaScript has no safety features like this. Having said that, we did recently get private fields, so if that's supported in your environment, you should be able to protect your collection array that way.

class Collection {
    #array;
    constructor() {
        this.#array = []
    }
    add (thing) {
        if (isOK(thing)) this.#array.push(thing)
    }
    get (index) {
        return this.#array[index]
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You want to create a getter/setter. collection should be a getter/setter.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda