将返回值传递给另一个函数javascript

时间:2015-09-21 18:51:56

标签: javascript design-patterns decorator

给出以下代码:

 function Foo() {};
 Foo.prototype.one = fluent(function(a , b) {
    return a + b;
 });
 Foo.prototype.two = fluent(function(c) {
    var d = c + 0.15; //0.15 cause I just couldnt thougth anything else at this moment...
    return d;
 });

好的,现在一切都很好,现在让我们说流利的是一个装饰功能,可以让我像这样实现它:

var test = new Foo();
test.one(10, 5).two(); //here is the problem...

认为这是一个承诺,我怎么能修改这个代码,以便使返回的值为2?意思是,c应该是返回值one(),同时保持样本实现。

这是fiddle;

1 个答案:

答案 0 :(得分:3)

我建议fluent的以下定义。请注意,如果需要,最终返回值位于this.$lastReturn

function fluent(impl) {
  return function() {
    // Convert arguments to a real array
    var args = Array.prototype.slice.call(arguments);

    // Prepend the last return value for this object
    if(typeof this.$lastReturn != 'undefined')
      args.unshift(this.$lastReturn);

    // Invoke the function and save the return value
    this.$lastReturn = impl.apply(this, args);

    // Return this to allow chaining of the next fluent call
    return this;
  }
}