2013-08-07 164 views
-2

如何得到這個返回值x + y + z而不是錯誤?函數返回返回函數的函數javascript

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

該代碼工作正常。你想實現什麼?不清楚你在問什麼。 –

+1

這裏不需要「新建」,你可以稱它爲「A(2)(3)(4)」或「var f = A(2)」。 var g = f(3);警報(克(4));',幾乎相同... – yent

+0

ye ..感謝您的好回答。請做出答案。傑夫......不,它不工作,你試過嗎? 「B未定義」。擺脫....它返回的x + y + z。只是一個概念證明。 – mike628

回答

2

像yent說,沒有 「新的」 S是必要的。 「新」返回一個實例。

例如(雙關語意):

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不在你調用的範圍內。其次,回到咋說的話。由於每個函數都返回一個函數,我們稱之爲返回的函數。

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

我希望幫助!