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

236
Visualizações
How do I access the properties in every instance of a class whithin another class?

I need to access the values of every instance of a class, and compare them.

So first, I get my properties:

class One {
    constructor(){
        this.properties = new Properties();
    }
}

Then, I need to read every instance that is created (in any number) and use them as arguments:

class Two {
    check(){
        if (/* arguments that contain info on all instances of class One */) {
            // code
        }
    }
}

Then I need to create instances of class Two, and call the check() function.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a static property on your class One in order to store the instances when you call it with new, and later you call the static property to get an array of all instances, take a look:

// just to complement the example
class Properties {
  name
  constructor(name) {
    this.name = name
  }
}

class One {
    // here is the static property where you will store the instance
    static allInstances = [];
    properties
    constructor(name){
      this.properties = new Properties(name);

      // here you will store the class instance
      // every time it's created
      One.allInstances.push(this)
    }
}

const instance1 = new One("instance1")
const instance2 = new One("instance2")
const instance3 = new One("instance3")

console.log(One.allInstances)
// (3) [_One {...}, _One {...}, _One {...}]

class Two {
  constructor() {}

  check(instanceNames){
    // here I'm logging the name of each instance
    instanceNames.forEach(instance => 
      console.log(instance.properties.name))
  }
}

const instanceOfTwo = new Two()

// pass the array of all instances with One.allInstances
instanceOfTwo.check(One.allInstances)

See the complete example, to know more about static methods and properties check this out.

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