2017-03-01 84 views
-1

我需要訪問FUNC1的論點FUNC2當我把它叫做在FUNC2的說法,這裏是帶註釋的代碼:你最終不得不函數作爲參數到另一個函數的JavaScript

let func1 = (x, y) => x + y; 

let func2 = function(func1) { 
    /* How can i get access to arguments of func1 here, when i call it like that: func2(func1(1, 2)); */ 
    return func1; 
} 

func2(func1(1, 2)); 
+4

你沒有傳遞函數作爲參數,你傳遞它的返回值!最後一行與'funct2(3)'相同;'! –

+3

如果你想知道參數,你需要做一些類似func2(func1,1,2)的操作。 – juvian

+0

我不相信你不能按你想要的方式做你想做的事。你能更清楚地瞭解你的最終目標嗎? –

回答

0

您可以嘗試將func1的參數傳遞給對象並返回對象。這將意味着改造我想象的應用程序的其他部分,但它不應該工作太多。如果箭頭沒有參數,則必須使用常規函數來完成。 jsbin of the code running here

const func1 = function(x, y) { 
    const args = arguments 
    return { 
    args: args, 
    main: x + y, 
    } 
} 

const func2 = function(func1) { 
    const otherArguments = func1.args 
    console.log(otherArguments) 
    return func1.main; 
} 

func2(func1(1, 2)); 
0

func1在自己的函數:

let func1 = (x, y) => x + y; 

let func2 = function(func1) { 
    return (...args) => { 
     // args is now the arguments that are being passed to func1 
     return func1(...args); 
    } 
} 

// Call it like this: 
func2(func1)(1, 2); 

這應該得到你所需要的,因爲伊布在他的評論中提到的,你傳遞它的返回值。 func2(func1(1, 2))變成func2(3)

+0

這看起來比我的答案好 – spirift

相關問題