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

170
Vistas
How to optionally add a method to a chain in javascript?

I have this chain of methods

MyObject.methodA().methodB().methodC()

Suppose I want methodB() to be added or changed based on some condition:

const inclueMethodB = false;
// change method based on condition
MyObject.methodA().(inclueMethodB ? methodB() : method123()).methodC()
// add method based on condition
MyObject.methodA().(inclueMethodB && methodB()).methodC()

Is there a way to do this in javascript?

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

0

I can't think of a way to optionally call a method like that.

If you were choosing between two methods, you could use a subscript where the method name is specified dynamically:

MyObject.methodA()[includeB1 ? "methodB1" : "methodB2"]().methodC()

You could achieve your original goal by defining a method that doesn't do anything except return the same thing that methodB() does. If this is a fluent interface where all the methods just return this, it could be:

doNothing() {
    return this;
}

Then you could write:

MyObject.methodA()[includeB ? "methodB" : "doNothing"]().methodC()

But this all seems unnecessarily complex and confusing. Just use ordinary if statements, which express the intent clearly:

let temp = MyObject.methodA();
if (includeB) {
    temp = temp.methodB();
}
temp.methodC();
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