在任何JavaScript文件,如果你寫的東西,如:
justFunction();
//function declaration
function justFunction()
{
alert("something");
}
這將調用justFunction( )並顯示警報。定義這樣的函數稱爲函數聲明。
現在有另一種方式,如果你喜歡寫東西
anotherFunction();
// Function Expression
var anotherFunction = function() { alert ("something"); }
雖然anotherFunction是一個函數在這裏,這將在控制檯給出錯誤定義一個函數
var anotherFunction = function() { alert ("something")}
現在。這被稱爲函數表達式。
背後的原因是函數聲明負荷在執行任何代碼之前。而函數表達式只在解釋器到達那行代碼時加載。所以如果你在加載之前試圖調用一個函數表達式,你會得到一個錯誤。
但是,如果你調用一個函數聲明,它會一直工作。因爲在載入所有聲明之前不能調用代碼。所以你必須在定義之後總是調用函數表達式。
// Function Expression
var anotherFunction = function() { alert ("something"); }
anotherFunction();
現在函數表達式可以立即由相同的
var anotherFunction = function() { alert ("something"); }(); //paranthesis added
匿名函數之後加入括號此代碼段稱爲和上面做同樣的事情(顯示警報)。現在anotherFunction變量與上面的不一樣,因爲它現在賦值了,匿名函數將返回。現在它不返回任何東西,所以anotherFunction是未定義的。所以如果你寫的東西類似
var anotherFunction = function() { alert ("something"); }();
anotherFunction(); //error
這將給出一個錯誤,因爲匿名函數不返回任何函數。如果其返回類似
var anotherFunction =
function() { alert ("something"); return "some string"; }(); //returns string
anotherFunction現在是一個字符串變量。如果:
var anotherFunction = function() { alert ("something"); return function(){
alert("somethingElse")
}; }(); // returns function
現在anotherFunction是一個函數,可以這樣調用anotherFunction().
你可以傳遞參數給這個函數表達式像
var anotherFunction = function(p1,p2) { console.log(p1);
console.log(p2); }(param1,param2); //param1,param2 are parameters
一個函數表達式之間的主要區別而函數聲明是可以通過使用一組圓括號來立即調用(調用)函數表達式,但函數聲明不能。
現在,如果我們不想將函數表達式分配給一個變量,那麼我們必須將它寫在括號內。
(function() { alert ("something");});
,並呼籲它,我們需要在末尾添加另一組括號像
(function() { alert ("something"); }());
而且與早先,我們也可以向它傳遞參數,如:
(function(param){ console.log(param); }(param));
這種類型的功能是稱爲IIFE的## Heading ##(立即調用函數表達式)。
IFFE只是一個匿名函數(沒有連接到它的名字),其被纏繞立即一組括號內和稱爲(調用)。
(function(){ }());
REFERNCE
anonymus功能,而不是 –
$立即調用函數,用'window'對象作爲參數。 –
它被稱爲IIFE(立即調用函數表達式)。有關詳細說明,請參閱http://benalman.com/news/2010/11/immediately-invoked-function-expression/。簡而言之,這是創建立即運行的私有函數上下文的一種方式。這與全球背景是分離的。 – jfriend00