Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!