2013-02-16 22 views
0

這是有史以來最令人困惑的事情。標題可能沒有多大意義。我盡力了。希望我能清楚。 好吧,我正在看谷歌頻道API的井字遊戲例子。將函數表達式傳遞給帶有變量的新函數()

在javascript部分。

他們有這樣的事情;

sendMessage = function(param) { 
    alert(param); 
    //this part actually sends message to server, 
    //for simplicity lets assume it pops up alert.  
    } 

init = function(){ 
    var input = 3; 
    var submitButton = document.getElementById('submitButton'); 
    submitButton.onclick = new Function('sendMessage(' + input + ')'); 
} 

setTimeout(init, 100); 

這會彈出警告並打印3.我不確定這是如何工作的。但它的工作。如果可以解釋的話,那也會很棒。我找不到其他地方使用新的Function()。

的問題是,如果輸入的是一個字符串,

var input = "test"; 

,這並不工作,並沒有警覺彈出。

感謝您的任何解釋和幫助。

+0

它的工作原理,它非常醜陋。你確定谷歌建議,而不是w3schools?提示:'Function()'~~'eval()' – 2013-02-16 07:28:39

+0

好好爲你自己檢查一下。那是他們做的。 – btevfik 2013-02-16 07:32:01

+0

http://code.google.com/p/channel-tac-toe/source/browse/trunk/index.html – btevfik 2013-02-16 07:33:00

回答

1

Function構造作品eval uating它的參數作爲函數體。

... = new Function('sendMessage(' + input + ')'); 

類似於

... = eval("function(){sendMessage("+input+")}"; 

對於數字input S,這工作,因爲他們的文字表述可以作爲數字文字。對於文本輸入來說,它不是。有限支持可以通過執行

... = new Function('sendMessage("'+input+'")'); 

的更一般的方式來獲得將是使用

... = new Function('sendMessage("'+JSON.stringify(input)+'")'); 

然而,我建議使用一個立即調用函數表達式(IIFE)代替,以避免任何形式的evalJSON對象,其不以非常舊的瀏覽器上存在的依賴性(IE < 8):

... = (function(input){ 
    return function(){ 
    sendMessage(input) 
    } 
})(input) 

或者,我F中的input變量不發生變化,則無需捕捉到它的價值:

... = function(){ sendMessage(input) } 

或者,如果你不使用this裏面的sendMessage,您可以使用bind(IE8需要勻場):

... = sendMessage.bind(undefined, input) 
+0

謝謝你的回答,這將不起作用 – btevfik 2013-02-16 07:51:28

0

當輸入一個字符串,函數調用變爲:

sendMessage(string) 

這實際上應該是:

sendMessage("string")sendMessage('string')

sendMessage = function(param) { 
    alert(param); 
    } 

init = function(){ 
    var input = '"string"'; 
    var submitButton = document.getElementById('submitButton'); 
    submitButton.onclick = new Function('sendMessage(' + input + ')'); 
} 

setTimeout(init, 100); 

這裏是fiddle看你怎麼可能使用。

+0

所以你應該設置'var input =''text'「;' – 2013-02-16 07:34:22

+0

非常感謝phil 。它的工作原理是 – btevfik 2013-02-16 07:36:46

+0

。但我仍然不知道新的Function()是如何工作的。該論據應該是功能主體。 'sendMessage('+ input +')'是函數體呢? – btevfik 2013-02-16 07:40:01

0

函數的參數被評估..也就是說它被執行。這就是它工作的原因。

當你傳遞一個字符串時,它不起作用,因爲你傳遞的字符串將被視爲一個對象或變量而不是字符串..我們都知道它不存在。

這個工程:

submitButton.onclick = new Function('sendMessage(3)'); 

這並不:

submitButton.onclick = new Function('sendMessage(test)'); //because test does not exist 

但這將

submitButton.onclick = new Function('sendMessage("test")'); 

所以如果你改變你的代碼:

submitButton.onclick = new Function('sendMessage("' + input + '")'); 

就萬事大吉了

+0

感謝您的答案。 – btevfik 2013-02-16 07:50:52

+0

如果'input'包含雙引號 – 2013-02-16 07:52:29