[JavaScript] IIFE 立即调用的函数表达式

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)."

  1. Learning JavaScript chapter 7: scope

你可能感兴趣的:(Other)