IIFE : immediately invoked function expression
定义形式如下:
(function() {
// this is the IIFE body
})();
例 1
const message = (function() {
const secret = "I'm a secret!";
return `The secret is ${secret.length} characters long.`;
})();
console.log(message); // "The secret is 13 characters long."
例 2
变量count
很像C++里的静态变量:
const f = (function() {
let count = 0;
return function() {
return`I have been called ${++count} time(s).`;
}
})();
console.log(f()); // "I have been called 1 time(s)."
console.log(f()); // "I have been called 2 time(s)."
- Learning JavaScript chapter 7: scope