Search code examples
javascriptchaining

How to chain in javascript yet get value in between


ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks


Solution

  • Trick is to use the valueOf() method.

    class Invoice {
    
      constructor(value) {
        this.value = value;
      }
    
      getAmount() {
        return {
          valueOf: _ => this.value,
          asCurrency: _ => '$' + this.value
        }
      }
    }
    
    const i = new Invoice(150);
    
    console.log(i.getAmount() + 10); // 160
    console.log(i.getAmount().asCurrency()); // '$150'