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

118
Vistas
How can I stop an object property access chain under certain conditions?
  1. Object A has an array of instances of Object B.
  2. Object A also has a getter method that takes in an index and returns the relevant Object B.
  3. Object B has a set of methods that can be called.

I'm trying to call the object B method using an object chain ( a.getB().method() )like below:

class ObjectB{
  foo(){return 'bar'}
}

class ObjectA{
  constructor(){
    this.list = []
   }
  addB(){this.list.push(new ObjectB)}
  getB(index) { if(index < this.list.length) return this.list[index]}
}

a = new ObjectA();
a.addB();
a.getB(0).foo(); // Works
a.getB(4).foo(); // Returns error, since getB(4) is undefined and has no foo()

I tried different else statements in getB() but I can't stop the script from trying to access 'output'.foo().

I tried a try catch in getB(), but I can't force it to give an error at getB(4). Is there a clean way from me to handle this potential issue without try/catching every instance of the last line?

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

0

Use the optional chaining operator: a.getB(4)?.foo() You can also add it for function calls: a.getB(4)?.foo?.(). This last solution works if getB(4) returns an object that is defined, but has no foo function.

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