2015-05-14 49 views
0

一個常見的錯誤引發錯誤:任何方式獲得,當函數,而不是運行它

a = myfunction; 

...而不是:

a = myfunction(); 

任何方式避免這種情況?

如果我們在對象中有這個函數,我可以向對象說些什麼來避免返回函數並且需要執行嗎?

+6

這是一個有效的JavaScript語句,拋出一個錯誤是沒有意義的。 – undefined

+0

我知道...但只有當你想得到一個功能 – civiltomain

回答

3

您可以使用typeof來檢查它是否是一個函數:

a = myfunction; 
var result; 

if (typeof a == "function") 
    // a was set to myfunction, not myfunction() 
    result = a(); 
else 
    // a was presumably set to myfunction() and not myfunction 
    result = a; 

這樣你可以調用的函數,如果它確實是一個功能,否則,你可以做點別的吧,假設這就是你」重新想要做。

+0

這是一個令人難以置信的快速downvote,照顧解釋它的推理? –

+0

不是我的失望,但我理解這個問題,因爲OP當他們實際上想要鍵入'a = myfunction();'時,他們想要減少不需要的錯誤,當他們意外地鍵入'a = myfunction;'時。這對此沒有幫助。 – JJJ

+1

但'a = myfunction'不會產生任何錯誤。這是一個有效的JS聲明。 – evolutionxbox

相關問題