What is the difference between assigning an IIFE's public members to a variable vs returning an object

女生的网名这么多〃 提交于 2019-12-23 17:07:09

问题


I've been looking at a lot of JavaScript code lately and I've seen two different ways of using assigning "public" properties of IIFE's.

The first is to create a variable and assign that variable to a property inside of the IIFE like so:

var public1;

(function(){
    var foo= "Foo", bar= "Bar";

    public1= {
        getFoo: function(){
            return foo;
        }
    };
}());

The second way I see is returning an object from the IIFE like so:

var public2 = (function(){
    var foo2= "Foo2", bar2= "Bar2";

    return {
        getBar: function(){
            return bar2;
        }
    };
}());

Is there a fundamental difference between these two ways or is it just a matter of preference? I've also created a fiddle so you can run or update the code if you'd like: http://jsfiddle.net/bittersweetryan/gnh79/3/


回答1:


There is no difference.

But I'd argue that the second one is a bit easier to maintain. When you change the variable name in the first example, you have to change it in the function as well.



来源:https://stackoverflow.com/questions/7197480/what-is-the-difference-between-assigning-an-iifes-public-members-to-a-variable

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