如何让它返回 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);
如何让它返回 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);
就像yent所说,没有“新的”是必要的。“新”返回一个实例。
例如(双关语):
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);
我希望这有帮助!