DEV Community

Rahul Chaudhary
Rahul Chaudhary

Posted on

Method chaining in Javascript

NOTE: In method chaining we return this

  1. Method Chaining example using ES6 class Method Chaining example using ES6 class
//method chaining using class object
class Calculator {
    constructor() {
        this.value = 0;
    }
    add(x) {
        this.value += x;
        return this;
    }
    sub(x) {
        this.value -= x;
        return this;
    }
    mul(x) {
        this.value *= x;
        return this;
    }
}

const obj = new Calculator();
obj.add(10).add(10).mul(2).value;
Enter fullscreen mode Exit fullscreen mode
  1. Method chaining example using javascript object shorthand Method chaining example using javascript object shorthand
//method chaining using object shorthand
let operations = {
    arrayValue: [],
    insert: function (x) {
        this.arrayValue.push(x);
        return this;
    },
    remove: function () {
        this.arrayValue.pop();
        return this;
    },
    filterMatching: function (x) {
        this.arrayValue = this.arrayValue.filter((e) => e === x);
        return this;
    },
};

operations.insert(1).insert(2).insert(3).remove().filterMatching(1).arrayValue;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)