使用立即执行函数表达式
立即执行函数表达式( IIFE - immediately invoked function expression)是一个立即执行的匿名函数表达式,它在Javascript中有一些很重要的用途。
(function() {
// Do something
}
)()
这是一个立即执行的匿名函数表达式,它在有JavaScript一些特别重要的用途。
两对括号包裹着一个匿名函数,使匿名函数变成了一个函数表达式。于是,我们现在拥有了一个未命名的函数表达式,而不是一个全局作用域下或在任何地方定义的的简单函数。
类似地,我们也可以创建一个命名过的立即执行函数表达式:
(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