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

125
Visualizações
Method chaning in javascript

How do I create method chaining functionality similar to jQuery in JavaScript. For eg. I have a main function where I can add different methods to it like add, subtract, multiply, divide, while main function taking one param.

Main(5).add(3).subtract(2).multiply(4).divide(6)

or

Main(10).subtract(5).add(5).divide(6)

It can be anything.

I was trying to put methods in an object in the return statement of the parent function, but it didn't work.

function main(a) {
    return {
        sum: function (b) {
            return a + b;
        },
        substract: function (c) {
            return a - c;
        },
    };
}

Please help

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

0

You could return an object of functions and store the result. At the end return only the value by taking a getter function.

function chain(value) {
    const methods = {
        add: v => {
            value += v;
            return methods;
        },
        substract: v => {
            value -= v;
            return methods;
        },
        get value() { return value; }
    }
    return methods;
}

console.log(chain(3).add(4).substract(5).value);

about 4 years ago · Juan Pablo Isaza Relatório

0

Change your code to:

function Main(a) {
    this.value = a;
}

Main.prototype.sum = function (a) {
    this.value += a;
    return this;
}

Main.prototype.subtract = function (a) {
    this.value -= a;
    return this;
}

Usage:

let var1 = new Main(5).sum(3).subtract(2); // var1.value = 6
about 4 years ago · Juan Pablo Isaza Relatório

0

Maintain a local variable n, perform the math on it, and then return this from each method.

function main (n = 0) {
  return {
    add: function(x) {
      n = n + x;
      return this;
    },
    subtract: function(x) {
      n = n - x;
      return this;
    },
    total: function () {
      return n;
    }
  };
}

const total = main(12)
  .add(2)
  .subtract(1)
  .total();
  
console.log(total);

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