JavaScript立即執行函數(Immediately Invoked Function Expression,簡稱IIFE)是一種在定義后立即執行的JavaScript函數。它被定義為一個匿名函數,并立即調用執行。IIFE的主要作用有以下幾點:
(function() {
var localVar = "Local Variable";
console.log(localVar); // 輸出 "Local Variable"
})();
console.log(localVar); // 報錯,因為 localVar 在外部作用域中沒有定義
(function() {
console.log("This code will execute immediately!");
})();
(function(someVar) {
console.log("Passed variable: " + someVar);
})("Hello, World!"); // 輸出 "Passed variable: Hello, World!"
var module = (function() {
var privateVar = "Private Variable";
function privateFunction() {
console.log("This is a private function.");
}
return {
publicFunction: function() {
console.log("Accessing private variable: " + privateVar);
privateFunction();
}
};
})();
module.publicFunction(); // 輸出 "Accessing private variable: Private Variable" 和 "This is a private function."
(function(callback) {
setTimeout(function() {
callback("Hello from setTimeout!");
}, 1000);
})(function(message) {
console.log(message); // 輸出 "Hello from setTimeout!",延遲1秒
});