2014-03-26 176 views
0

好吧,這是很難解釋的,但我在這裏演示了我正在嘗試完成的東西。在一個函數中傳遞一個參數在另一個函數中被「參考」傳遞

我認爲這與How can I pre-set arguments in JavaScript function call? (Partial Function Application)有關,但我無法弄清楚如何將這篇文章中提到的方法應用到我的場景中。

我有三個功能。

  • func1。一個函數傳遞給func2並被其調用一次 func2完成其業務。
  • func2。將要調用的函數(func1) 作爲參數接收的函數。
  • func3。調用func2的函數。

我想傳遞一個參數給func3,它傳遞給func2中的func1。

例:

<input type='button' id='testButton' onclick='func3()' value='Click Me' /> 
<input type='button' id='testButton2' onclick='func3a(true)' value='Click Me Also' /> 

func3 = function (aBool) { 
     func2(func1); 
    } 

// I want to be able to pass a parameter to the function 
// that gets called in func2 
func3a = function (aBool) { 
    func2(func1(aBool)); 
} 

func1 = function (data, myBool) { 
    alert(data[0] + ' ' + myBool); 
} 


// Cannot Change this function 
func2 = function (func) { 
    var data = []; 
    data[0] = "Hello World" 
    func(data); 
} 

回答

2

你可以換傳給func2與內聯函數的函數。然後將該呼叫委託給傳遞附加參數的func1

例如爲:

function func3a(aBool) { 
    func2(function(data) { 
    func1(data, aBool); 
    }); 
} 

http://jsbin.com/qamigura/1/

+0

謝謝,這在我的例子和實際代碼中都有效。我最近在YouTube上觀看了Crockford的一些視頻,而且我知道我曾經在某處看到過這個視頻。只是沒有把我的手指。 – Popo

2

您可以使用Function.prototype.bind不僅在功能(this)執行的背景下,同時也是第一個參數調用該函數與綁定。

func3 = function (aBool) { 
    func2(func1.bind(null,aBool)); 
} 


func1 = function(myBool, data) { 
    alert(data[0] + ' ' + myBool); 
} 

請注意,我不得不改變FUNC1的簽名,以獲得布爾作爲第一個參數,以便FUNC2可以設置第二個參數時,它調用它。

bind的實現與Yoshi在實踐中的回答相似。請注意,他的答案不會對參數的順序施加任何限制。

+0

謝謝,我也會通過你的回答,我想了解它是如何工作的。雖然,這可能會更難實現,因爲我的實際代碼有更多的參數。 – Popo

+0

我只是想發佈這裏,因爲綁定是準確的部分功能應用。它更受限制,但寫起來也更容易,所以你應該在適合的時候使用它。 – Tibos

相關問題