【问题标题】:functions return functions that return functions javascript函数返回函数返回函数 javascript
【发布时间】:2013-08-07 13:30:54
【问题描述】:

如何让它返回 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);

【问题讨论】:

  • 代码运行良好。你想达到什么目标?不清楚你在问什么。
  • 这里不需要“新”,你可以称它为A(2)(3)(4)var f = A(2); var g = f(3); alert(g(4));,几乎一样...
  • yent..感谢您的出色回答。请把它作为一个答案。杰夫......不,它不起作用,你试过了吗? “未定义的 B”。摆脱....它返回 x+y+z。只是一个概念证明。
  • 定义“不起作用”。据我们所知,您希望程序说明与未定义函数有关的运行时错误。在这种情况下,它可以完美运行。

标签: javascript closures


【解决方案1】:

就像yent 说的,没有“新的”是必要的。 "new" 返回一个实例。

例如(双关语):

function foo(a){
    return a;
}

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

但现在谈谈你的问题。就像 rid 说的那样,B 是在函数 A 的范围内声明的。所以,你的 new outer(B(9)); 会抛出一个错误,因为 B 在你调用它的范围内不存在。

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

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

希望对你有所帮助!

【讨论】:

    猜你喜欢
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2016-04-25
    • 1970-01-01
    相关资源
    最近更新 更多