Reputation: 22500
I have one simple object calculation function .I was pass the object resultant data in to another object function like the chain reaction
example like:
str.replace().replace().replace()
They will pass the resultant data of first replace to 2nd replace like the chain reaction.
So i want to created the below code .But not working in my case .
See the below snippet
var m=function(data){
return {
str :data,
plus:function(b){
this.str = this.str+b;
return this.str;
},
min:function(a){
this.str = this.str-a
return this.str;
}
}
}
console.log(m(5).plus(1).min(3))
If 5
add with 1
is 6
.Then pass the 6
into min()
function for reduce 3
.finally console.log result 3
.But It have some here .Please help to solve my problem.
Thanks
Upvotes: 2
Views: 232
Reputation: 13120
Another closer way, we can return this
separately, at initialisation, and every other method calls.
Doing it this way is a real chain, as this
called in the plus
and min
function is the incoming object, it's not a recomposition.
We often see both styles.
function m(n) {
this.value = n.value
this.plus = (n) => {this.value = this.value + n.value; return this}
this.min = (n) => {this.value = this.value - n.value; return this}
return this // Only at initialisation
}
console.log(m({value: 5}).plus({value: 1}).min({value: 3}).value)
Upvotes: 0
Reputation: 386680
I suggest to use an object and return that object after a method call. For better use, you could implement toString
and valueOf
methods to use the return value directly.
What you need is to return the whole object, for all methods which a chainable.
var m = function(value){
var obj = {
value: value,
plus: function (b) {
obj.value += b;
return obj;
},
min: function(a) {
obj.value -= a;
return obj;
},
toString: function () { return obj.value; },
valueOf: function () { return obj.value; }
}
return obj;
}
console.log(m(5).plus(1).min(3).value);
alert(m(5).plus(1).min(3));
console.log(m(3).plus(7) - m(5).min(1));
Upvotes: 2
Reputation: 906
var m=function(data){
return {
str :data,
plus:function(b){
this.str = this.str+b;
return this;
},
min:function(a){
this.str = this.str-a
return this;
}
}
}
console.log(m(5).plus(1).min(3).str)
For creating chain like method calls you need to return 'this' from the function after which you want to the chain to continue
Upvotes: 1