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

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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