简体   繁体   中英

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

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM