JavaScript立即執(zhí)行函數(shù)(Immediately Invoked Function Expression,簡稱IIFE)是一種在定義后立即執(zhí)行的JavaScript函數(shù)。它被定義為一個(gè)匿名函數(shù),并立即調(diào)用執(zhí)行。IIFE的主要作用有以下幾點(diǎn):
(function() {
var localVar = "Local Variable";
console.log(localVar); // 輸出 "Local Variable"
})();
console.log(localVar); // 報(bào)錯(cuò),因?yàn)?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秒
});