NOTE: In method chaining we return this
- 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;
- 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;
Top comments (0)