立即调用函数表达式 (IIFE) 是一个 JavaScript 函数,一旦定义就会运行。它通常用于避免污染全局范围或为变量创建私有范围。
这是一个 IIFE 的简单示例:
(function() { var message = "Hello from IIFE!"; console.log(message); })();
Hello from IIFE!
当您想要创建新作用域时,IIFE 非常有用,特别是为了保护变量不被函数外部访问或修改:
(function() { var counter = 0; // This counter is private and can't be accessed from outside function increment() { counter++; console.log(counter); } increment(); // Logs: 1 increment(); // Logs: 2 })(); console.log(typeof counter); // Logs: "undefined", because `counter` is not accessible here.
这确保了像 counter 这样的变量保持私有,并且不会被代码的其他部分意外修改或访问。
以上是立即调用函数表达式 (IIFE)的详细内容。更多信息请关注PHP中文网其他相关文章!