1

只有函數的表達式可以立即調用:在JavaScript中,爲什麼我不能立即調用函數聲明?

(function() { 
    var x = "Hello!!";  // I will invoke myself 
})(); 

但不是函數聲明?這是因爲函數聲明被掛起並且已經立即執行?

編輯:資源我引用

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

http://markdalgleish.com/presentations/gettingclosure/

+0

函數x(){}與var x = function(){}相同,並且顯式變量「returns」void而不是賦值,這就是爲什麼你不能說alert (var x = 1),但你可以說alert(x = 1);對於函數來說是一樣的 – dandavis

回答

1

不知道你意味着什麼 - 如果你運行你已經表明,它仍然會立即執行

方式的函數聲明

(function declaredFn(){ 
 
    document.getElementById('result').innerHTML='executed'; 
 
}());
<div id="result"></div>

+0

這不是af unction聲明,如果你[稍後調用'declaredFn'](http://jsfiddle.net/faxbLfot/),它會導致引用錯誤。 – Teemu

+0

@Teemu - 有趣的是,你是對的 – codebox

+0

對不起,爲了澄清,我已經知道只有函數表達式可以被立即調用,但是你不能立即調用函數聲明。我想知道這是爲什麼。 – amoeboar

2

要清除混亂

什麼是函數聲明

// this is function declaration 
function foo(){ 
    // code here 
} 

OR

//this is ok, but without name, how would you refer and use it 
function(){ 
    // code here 
} 

立即撥打它,你這樣做

function foo(){ 
    // code here 
}() 

什麼是在第二種情況下,你已經創建了一個匿名function.you函數表達式

// this is a function expression 
var a = function foo(){ 
// code here 
}; 

var a = function(){ 
    // code here 
}; 

還是要函數的引用通過可變a。所以你可以這樣做a()

調用函數表達式

var a = (function(){ 
    // code here 
}()); 

變量a存儲在與函數的結果(如果從函數返回),並失去了參照功能。

在這兩種情況下,您都可以立即調用函數,但結果與上面指出的不同。

2

Source

」 ......有趣的是,如果你要指定該功能的名稱,並把括號緊隨其後,解析器也會拋出一個SyntaxError,但出於不同的原因,雖然括號放置在表達式之後,表達式是一個要調用的函數,放置在語句之後的parens與前面的語句完全分離,並且僅僅是一個分組操作符(用作控制評估優先級的手段)。「

// While this function declaration is now syntactically valid, it's still 
// a statement, and the following set of parens is invalid because the 
// grouping operator needs to contain an expression. 
function foo(){ /* code */ }(); // SyntaxError: Unexpected token) 

// Now, if you put an expression in the parens, no exception is thrown... 
// but the function isn't executed either, because this: 

function foo(){ /* code */ }(1); 

// Is really just equivalent to this, a function declaration followed by a 
// completely unrelated expression: 

function foo(){ /* code */ } 

(1); 

因此,你需要寫功能

(function doSomething() {})(); 

,因爲這告訴解析器來評價它作爲一個函數表達式,而不是一個函數聲明。和所有你正在做的,然後立即調用表達式

+0

稍後有可能再次調用這個IIF,例如在一個Event Listener中? –

相關問題