Hi fellow developers,
I was asked to implement the following
let num = new Mathematics(5).add(5).sub(8).add(8).getVal();
console.log(num) // 10
Below is my implementation:
function Mathematics(val) {
this.value = val;
this.add = (val)=>{
this.value += val;
}
;
this.sub = (val)=>{
this.value -= val;
}
this.getVal = ()=>{
return this.value;
}
}
Now when I run this it like below it will thrown an error.
let num = new Mathematics(5).add(5).sub(8).add(8).getVal();
But if I call it like below the code works perfectly
const num = new Mathematics(5);
num.add(5);
num.sub(8);
num.add(8);
console.log(num,getVal()); // 10
Upon searching online, I found that what was missing was that I needed to return this in the add() and sub() methods.
Can somebody explain why I have to return this and, moreover, what is the difference between the two ways by which I am calling methods?
function Mathematics(val) {
this.value = val;
this.add = (val)=>{
this.value += val;
return this;
}
;
this.sub = (val)=>{
this.value -= val;
return this;
}
this.getVal = ()=>{
return this.value;
}
}
>Solution :
What you’re doing is called function chaining.
When you do .add(5).sub(8), you’re calling .sub on the result of the function call to .add(5). If you don’t return this, and instead return nothing, then you’d be calling .sub on undefined.
You can also implement chaining like this:
class Mathematics {
constructor(val) { this.value = val; }
add(val) {
this.value += val;
return this;
}
sub(val) {
this.value -= val;
return this;
}
get val() {
return this.value;
}
}
let {val} = new Mathematics(5).add(5).sub(8).add(8);
console.log(val);