Kevkeev13
Kevkeev13

Reputation: 389

Method chaining in JS

let's say this :

var method = function(number) {
  this.number = number;

  this.add = function(param) {
    this.number = this.number + param;
    return this
  }
  this.multiply = function(param) {
    this.number = this.number * param;
    return this.number
  }

}

If I do :

var newMeth = new method(2);
var result = newMeth.add(2).multiply(2);
console.log(result) // Will return 8

But my main concern is if I want to do :

var newMeth = new method(2);
var result = newMeth.add(2);

I would like to know how it would be possible in that case that result return me "4" instead of method {number: 4, add: ƒ, multiply: ƒ}

But still return me 8 if I do

var result = newMeth.add(2).multiply(2);

Any help would be appreciate. Thank you all.

Upvotes: 0

Views: 49

Answers (2)

VLAZ
VLAZ

Reputation: 29089

You can define a valueOf method on your object. You can explicitly call it to get the number but it will also be implicitly called when converting the object to a primitive:

var method = function(number) {
  this.number = number;

  this.add = function(param) {
    this.number = this.number + param;
    return this
  }
  
  this.multiply = function(param) {
    this.number = this.number * param;
    return this
  }
  
  this.valueOf = function() {
    return this.number;
  }
}

var num = new method(2)
  .add(3)
  .multiply(7);
console.log(num.valueOf());
console.log(num + 3);
console.log(num + " bottles on the wall");

Upvotes: 1

Pavel Lint
Pavel Lint

Reputation: 3527

You could define the val() method on your chain that would return the number, and use it like this:

var result = newMeth.add(2).multiply(2).val();
// OR
var result = newMeth.add(2).val();
// OR
var result = newMeth.val();

Upvotes: 2

Related Questions