从方法链的末尾获取不同的输出
Get different output from the end of a method chain
如果我有一个看起来像这样的方法链:
object.value.add(1).multiply(2);
对象是这样的:
var object = {
"value":1,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
}
}
这将输出:
{
"value":4,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
}
}
但我希望它输出:
4
这可能吗?
而且我不想为输出制作另一种方法,我希望 "multiply" 方法(和 "add" 方法)乘以整个对象,如果它不是方法链中的最后一个(所以该方法链接是可能的),但是当它最后一次我希望它输出 "value" 属性时。
该方法没有有效的方法(甚至可能没有方法)知道它是否是链的最后一个成员。
为什么不是这个?
object.add(1).multiply(2).value
您也可以在非常具体的场景中利用 valueOf
,但不能将其用作通用策略。
var object = {
"value":1,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
},
valueOf: function () { return this.value; }
};
console.log(object.add(4).multiply(2) / 2); //5
如果我有一个看起来像这样的方法链:
object.value.add(1).multiply(2);
对象是这样的:
var object = {
"value":1,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
}
}
这将输出:
{
"value":4,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
}
}
但我希望它输出:
4
这可能吗? 而且我不想为输出制作另一种方法,我希望 "multiply" 方法(和 "add" 方法)乘以整个对象,如果它不是方法链中的最后一个(所以该方法链接是可能的),但是当它最后一次我希望它输出 "value" 属性时。
该方法没有有效的方法(甚至可能没有方法)知道它是否是链的最后一个成员。
为什么不是这个?
object.add(1).multiply(2).value
您也可以在非常具体的场景中利用 valueOf
,但不能将其用作通用策略。
var object = {
"value":1,
"add":function(x){
this.value = this.value + x;
return this;
},
"multiply":function(x){
this.value = this.value * x;
return this;
},
valueOf: function () { return this.value; }
};
console.log(object.add(4).multiply(2) / 2); //5