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

148
Visualizações
How can I chain a javascript method with a value also

So if I want to do something like five().plus().five().equals() // this should return 10 How can I achieve this? I understand method chaining when the functions return another function but what about when you want to use a value in the next function in the chain?

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

0

class Stack{
  constructor(state=0){
    this.state = state;
    this.op = null;
  }
  pushVal(v){
    switch(this.op){
      case '+': this.state += v; break;
      case '-': this.state -= v; break;
      default: this.state = v; break;
    }
  }
  plus(){
    this.op = '+';
    return this;
  }
  minus(){
    this.op = '-';
    return this;
  }
  equals(){
    return this.state;
  }
}


consts = {
  five: 5,
  six: 6,
  seven: 7
};


for(const n in consts){
  Stack.prototype[n] = function (){
    this.pushVal(consts[n])
    return this;
  }
}

five = () => new Stack(5)

/// Now we can run what you want

console.log(five().plus().five().equals())
// and some extension of it
console.log(five().plus().five().minus().seven().equals())

about 4 years ago · Juan Pablo Isaza Relatório

0

Chaining is a Concept in JS in which we can repeatedly call the properties of an object.

What you can do, if it is just about chaining,

let obj = {
  num:0,
  get(){
    console.log(this.num);
    return this;
  },
  set(num){
    this.num = num;

    return this;
  },
  add(a){
    this.num = this.num+a;
    return this;
  },
  subtract(a){
    this.num = this.num-a;
    return this;
  },
  divide(a){
    this.num = this.num/a;
    return this;
  },
  multiply(a){
    this.num = this.num*a;
    return this;
  }
}

obj.set(5).add(2).multiply(3).divide(7).add(3).get();

The most important part in chaining is returning this

You can read more about it at: https://medium.com/technofunnel/javascript-function-chaining-8b2fbef76f7f

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