简体   繁体   中英

What is the difference and benefits/drawbacks between object literals and functions that return an object inside an IIFE?

So to clarify the question, I understand what an IIFE and object literal is. However, I am unsure what the difference(s) is/are between these two examples (aside from the fact that one is a function and the other is an object literal):

Example 1:

(function(){
    var myStuff = {
        arbitraryValue: 42
    }
    return myStuff.arbitraryValue;
})();


Example 2:

(function(){
    var myStuff = function() {
        return {
            arbitraryValue: 42
        };
    }
    return myStuff().arbitraryValue;
})();


Both examples return the same results, and are called (almost) the same way. But:

1) What are the fundamental differences between them?
2) Is there a benefit to using one over the other?
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue . How is that possible?
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
5) Are either of these examples considered "best practice," or is there another option?

Many thanks in advance!

1) What are the fundamental differences between them?

The first (probably) uses less CPU cycles because it has one less function call and is less to write. It's also easier to understand so is likely easier to maintain.

2) Is there a benefit to using one over the other?

The first uses less code and is likely easier to understand and maintain.

3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?

Perhaps using get , a feature of JavaScript™ but not ECMAScript .

4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?

Yes, though you haven't shown what is done with the returned value. In the example it disappears into the ether.

5) Are either of these examples considered "best practice," or is there another option?

"Best" infers a complarison with other things that are less preferred based on objective criteria. Without those criteria (which might be some of: speed, robustness, maintainability, support or other features, desirable or not) it can't be determined.

If you propose a circumstance where you'd like to use one or the other, advice can be given on whether there are better ways or not based on the criteria suggested (or others you may have) and in comparison to alternatives.

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