函数返回返回函数javascript的函数

时间:2013-08-07 13:30:55

标签: javascript closures

如何让它返回x + y + z的值而不是错误?

function A (x) {
    return function B (y) {
        return function(z) {
            return x+y+z;
        }
    }
};

var outer = new A(4);
var inner = new outer(B(9));
inner(4);

1 个答案:

答案 0 :(得分:2)

就像说的那样,不需要“新的”。 “new”返回一个实例。

例如(双关语):

function foo(a){
    return a;
}

foo(4);    // this will return 4, but
new foo(); // this will return a 'foo' object

但现在问你的问题。就像摆脱说的那样,B在函数A的范围内被声明。因此,你的new outer(B(9));将抛出一个错误,因为B在你调用它的范围内不存在。

其次,回到所说的话。由于每个函数都返回一个函数,我们调用返回的函数。

function A (x) {
    return function B (y) {
        return function C (z) {
            return x+y+z;
        }
    }
};

var f = A(2); // f is now function B, with x = 2
var g = f(3); // g is now function C, with x = 2, and y = 3
var h = g(4); // Function C returns x+y+z, so h = 2 + 3 + 4 = 9

但是,我们可以使用以下“快捷方式”:

A(2)(3)(4);
// each recursive '(x)' is attempting to call the value in front of it as if it was a function (and in this case they are).

解释一下:

A(2)(3)(4) = ( A(2)(3) )(4) = ( ( A(2) )(3) )(4);

// A(2) returns a function that we assigned to f, so
( ( A(2) )(3) )(4) = ( ( f )(3) )(4) = ( f(3) )(4);

// We also know that f(3) returns a function that we assigned to g, so
( f(3) )(4) = g(4);

我希望有所帮助!