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

passing a returned value to another function, javascript

给定以下代码:

 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;
 });

好的,目前一切都很好,现在让我们说 fluent 是一个装饰器函数,它允许我像这样实现它:

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

考虑到这是一个承诺,我该如何修改这段代码才能使一个的返回值对两个可用???也就是说,c 应该是 one() 的返回值,同时保持示例实现。

这里是 fiddle;

我建议fluent的定义如下。请注意,如果需要,最终的 return 值位于 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;
  }
}

这个解决方案利用了的答案,对返回值或链的特性做了一些扩展。

Javascript 提供请求对象原始值的可能性,Object.prototype.valueOf() 。在这种情况下,如果我们需要一个值,它可以用来获取一个值,而在其他情况下,有返回的对象。

有关详细信息,请查看这篇文章 Object-to-Primitive Conversions in JavaScript

另一个增加是fluent处的参数控制和方法的调用。如果给出参数,则采用参数,如果未给出,则使用 this.$lastreturn

function fluent(impl) {
    return function () {
        var args = Array.prototype.slice.call(arguments);
        // Prepend the last return value for this object only if arg length is 0
        if (!args.length && typeof this.$lastReturn !== 'undefined') {
            args.unshift(this.$lastReturn);
        }
        this.$lastReturn = impl.apply(this, args);
        return this;
    }
}
function Foo() { };
Foo.prototype.one = fluent(function (a, b) {
    return a + b;
});
Foo.prototype.two = fluent( function (c) {
    return c + 0.77;
});

// this returns the primitive value
Foo.prototype.valueOf = function (c) {
    return this.$lastReturn;
};

var test = new Foo();
var x = test.one(10, 5);
document.write(x + '<br>');        // 15
document.write(typeof x + '<br>'); // object
var y = x.two();
document.write(y + '<br>');        // 15.77
document.write(typeof y + '<br>'); // object
var z = y.two(35);
document.write(z + '<br>');        // 35.77
document.write(typeof z + '<br>'); // object