使用立即函式表達式
稱作「Iffy」(IIFE - immediately invoked function expression)是一個匿名函式表達式,而且可以立即被調用,在 JavaScript 中有一些相當重要的用途。
(function() {
// Do something
}
)()
它是一個匿名函式表達式,而且可以立即被調用,在 JavaScript 某些部分中相當重要。
一對括號包著匿名函式,將匿名函式變成函式表達式或變數表達式。我們現在有一個未命名的函式表達式,它不是一個在全域 scope 內的簡單匿名函式或者是其他任何被定義的函式。
同樣的,我們也可以為立即函式表達式命名:
(someNamedFunction = function(msg) {
console.log(msg || "Nothing for today !!")
})(); // 輸出 --> Nothing for today !!
someNamedFunction("Javascript rocks !!"); // 輸出 --> Javascript rocks !!
someNamedFunction(); // 輸出 --> Nothing for today !!
更多細節,請參考以下網址 -
效能: jsPerf
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW