Immediately-Invoked Function Expression (IIFE) vs not

半腔热情 提交于 2019-11-28 02:13:18

Usually, you would have this :

        var myApp ={};
        (function() {
            console.log("Hello");
            var var1 = "mark";  
            myApp.sayGoodbye = function() {
                console.log("Goodbye");
            };
        })();

The main difference is that var1 doesn't clutter the global namespace. After this call, var1 is still the same than before (generally undefined).

As var1 can only be accessed from the function defineds in the closure, it is said "private".

Apart avoiding possible causes of conflicts, it's just cleaner not to keep global variables when useless.

Here, you don't have a local variable but a global one defined as this.var1. It's probably a bug, or the reason would be found elsewhere in the code.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!