我有一个简单的对象计算函数。我将对象结果数据传递给另一个对象函数,例如连锁反应
例如:
str.replace().replace().replace()
它们会将第一次替换的结果数据传递到第二次替换,就像链式反应一样。
所以我想创建下面的代码.但在我的情况下不起作用.
请参阅下面的代码片段
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))
如果5
添加1
则6
.然后将6
传递到min()
函数中,以减少3
.finally 控制台.log结果3
。但它这里有一些.请帮助解决我的问题。
谢谢
我建议使用一个对象并在方法调用后返回该对象。为了更好地使用,您可以实现toString
和valueOf
方法来直接使用返回值。
您需要的是返回整个对象,对于可链接的所有方法。
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));
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)
要创建类似链的方法调用,您需要从函数返回"this",之后您希望链继续
另一种更近的方法,我们可以在初始化时以及所有其他方法调用时分别返回this
。
这样做是一个真正的链,正如this
plus
中调用的那样,min
函数是传入的对象,它不是重构。
我们经常看到这两种风格。
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)