2015-04-01 40 views
0

案例1:功能,無需括號()

function square(x) { return x*x; } 
var s = square(); // Invoking with parentheses 
console.log(square(2)); 
console.log(s(2)); 

案例2:

function square(x) { return x*x; } 
var s = square;// invoking without parentheses 
console.log(square(2)); 
console.log(s(2)); 

功能都應該與調用()。那麼爲什麼它在案例1中返回undefined,但在案例2中工作正常?

+0

調用發生在表達單曲(2)',而不是'S = square'!?沒有任何爭論。 – Bergi 2015-04-01 20:51:13

+0

獲取'未處理的錯誤:'s'不是您的情況1的函數。 – Bergi 2015-04-01 20:52:34

回答

3

在情況1中,將調用('調用')square函數的返回值分配給s。但由於您沒有提供任何參數,因此您要求它計算undefined * undefined,即NaN(「不是數字」,即無法計算)。然後在你結束時s(2)我假設你得到一個錯誤,因爲s不是一個函數。

在情況2中,您沒有調用該函數,只是將函數對象本身分配給var s。這意味着它在您執行s(2)時有效,因爲s是對square函數的引用。

+0

像C#中的代表一樣? – ryanyuyu 2015-04-01 20:49:01

+0

我不知道,但可能不是一回事......重點是在Javascript中,函數是一種類似於任何其他類型的對象。 – Anentropic 2015-04-01 20:58:07

1

你的情況下,1分配ssquare()輸出。因此,你傳遞什麼,並分配到sundefined

分配ssquare沒有括號()的作品,因爲你要分配給s功能square,而不是它的輸出。

1

這裏案2個工程 - 請檢查意見爲更好地理解,

Case 1: 

function square(x) { return x*x; } 
var s = square(); // Invoking without any parameter 
console.log(square(2));//Invoking the actual function here with param 
console.log(s(2));//This is incorrect as s is storing the result of the `square()`. So this doesn't work 
Case 2: 

function square(x) { return x*x; } 
var s = square;// just declaring a variable 
console.log(square(2));//Invoking the actual function here 
console.log(s(2));//Invoking the actual function here with param. It works here