开发者

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

开发者 https://www.devze.com 2023-03-31 01:00 出处:网络
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.

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/b开发者_C百科ittersweetryan/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.

0

精彩评论

暂无评论...
验证码 换一张
取 消