Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between the two style of calling a constructor function?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading