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

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

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