How does an IIFE's being called immediately prevent it from polluting global scope?

前端 未结 2 1254
旧时难觅i
旧时难觅i 2020-12-18 16:53

In a Udacity lesson on immediately invoked function expressions (regarding the provided code snippet) it says:

The function that is being returned clo

相关标签:
2条回答
  • 2020-12-18 17:09

    How does an IIFE's being called immediately prevent it from polluting global scope?

    It doesn't.

    Being a function stops it polluting the global scope.

    Variables declared inside a function exist only within that function

    0 讨论(0)
  • 2020-12-18 17:19

    In modern JavaScript, you have let and block scope (and I'm pretty sure const has block scope, too), so you could just do this:

    let myFunction;
    {
        let hi = 'Hi!';
        myFunction = function () {
            console.log(hi);
        };
    }
    

    This creates myFunction without leaking hi into the surrounding scope.

    In traditional JavaScript, where you only have var and function scope, you could do this:

    var myFunction;
    function a_private_scope() {
        var hi = 'Hi!';
        myFunction = function () {
            console.log(hi);
        };
    }
    a_private_scope();
    

    a_private_scope limits the scope of hi, but (it being a function declaration) it needs to be called explicitly, and we still leak a name to the surrounding scope (this time it's a_private_scope, the name of the function-serving-as-a-scope).

    By using a function expression and immediately calling it, we avoid this second name pollution:

    var myFunction;
    (function () {
        var hi = 'Hi!';
        myFunction = function () {
            console.log(hi);
        };
    })();
    

    Now the only thing defined in the outer scope is myFunction. The anonymous function that serves as a scope for hi has no name it could pollute the surrounding scope with.

    Finally we can clean it up a bit by using return values, so we don't have to mention myFunction twice:

    var myFunction = function () {
        var hi = 'Hi!';
        return function () {
            console.log(hi);
        };
    }();
    

    (This also saves us a pair of ( ) because the function keyword doesn't appear at the beginning of a statement anymore.)

    0 讨论(0)
提交回复
热议问题