Immediately-Invoked Function [removed]IIFE) vs not

后端 未结 2 550
南笙
南笙 2020-12-07 04:36

I see a lot of code like:

var myApp ={};
(function() {
    console.log(\"Hello\");
    this.var1 = \"mark\";     //\"this\" is global, because it runs immedi         


        
2条回答
  •  死守一世寂寞
    2020-12-07 05:02

    One reason: wrapping your code in an anonymous function allows you to create a module which distinguishes a public API from private functions and variables that are only used internally to the module. This avoids polluting the global namespace.

    var myApp ={};
    (function() {
        console.log("Hello");
        this.var1 = "mark";
    
        function helper() {/*Some code here*/;}
    
        myApp.sayGoodbye = function() {
            helper()
            console.log("Goodbye");
        };
    })();
    

    I could say:

    var myApp ={};
    console.log("Hello");
    var var1 = "mark";
    
    function helper() {/*Some code here*/;}
    
    myApp.sayGoodbye = function() {
        helper()
        console.log("Goodbye");
    };
    

    But then the global scope includes a function called helper which is of no use to anyone using your module, and could lead to possible naming conflicts with other modules.

    I could alternatively just include helper as a method of myApp.

    var myApp ={};
    console.log("Hello");
    var var1 = "mark";
    
    myApp.helper = function() {/*Some code here*/;}
    
    myApp.sayGoodbye = function() {
        this.helper()
        console.log("Goodbye");
    };
    

    However, I may wish to prevent users from directly calling helper, in which case this won't do.

提交回复
热议问题