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秒
});