Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda