3

I'm trying to wrap a JavaScript object literal in a self executing anonymous function. The first code example below works fine, but the second doesn't and I'm not really sure why?

Works:

(function(){
    return MyApp = {
        init: function() {
            console.log('MyApp init');
        }
    }
})();

Doesn't Work:

(function(){
    var MyApp = {
        init: function() {
            console.log('MyApp init');
        }
    }
    return MyApp;
})();

As I understand things, the SEAF should execute and immediately return. That's why the first example returns MyApp as an object I can interact with. I thought assigning MyApp to a variable inside the SEAF and then returning it would do the same thing but in:

Uncaught ReferenceError: MyApp is not defined

Why?

5
  • 2
    In your first example you are assigning the result to the global variable named 'MyApp'. In the second case you are assigning the variable to a closure local variable named 'MyApp'. You have to assign the result of the closure execution somewhere, otherwise it gets lost. Commented Oct 17, 2013 at 21:11
  • 2
    Your code works just fine assuming you catch the return values. Commented Oct 17, 2013 at 21:11
  • As zzzzBov points out, it works just fine if you put var someName = (theClosureExecution) Commented Oct 17, 2013 at 21:12
  • What is "SEAF"? "IIFE"? Commented Apr 16, 2023 at 17:37
  • OK, SEAF is probably self-executing anonymous function. Commented Apr 16, 2023 at 17:41

3 Answers 3

3

Since the result of your SEAF (better named IIFE) is not used anywhere. It doesn't really matter what the function returns. Now compare

(function(){
    MyApp = {…}
})();

with

(function(){
    var MyApp = {…}
})();

The difference is that in the second function your variable is preceded by a var keyword which makes it local to the IEFE, while in the first function it is an implicit global (which you should avoid). That way, the second snippet doesn't assign to anything in the global scope, and accessing MyApp later from outside will fail with the error.

Better return some value that you then assign to a globally declared variable:

var MyApp = (function(){
    return {…};
})();
Sign up to request clarification or add additional context in comments.

2 Comments

if I'm using this to namespace my JavaScript code, is returning an object literal the best way to implement a Singleton pattern since I only really want one instance of the App available at any given time?
Yes, probably. If you don't have any local variables in the module, you can omit the IEFE; and it doesn't necessarily need to be an object literal but you could use any way to create object.
1

What your first example is doing is setting MyApp as a global variable - since the variable MyApp is not preceded by a var keyword or dot notation, it becomes global. It sounds like that's not actually an issue for you if you're putting MyApp in a self-executing function - you can really just remove the return statement from it - or even define other globals in the same function. You don't ever reference the result of your top-level function, so there's no use of that return.

Your second example sets MyApp as a local variable using var, so it's visible only inside of the context of the function that's running it.

Comments

0

Solution using arrow functions:

var myApp = (() => {
    return {
        init: () => console.log('MyApp init')
    };    
})();
myApp.init();

Explanation:

  • The global variable myApp is set to the result of an IIFE (Immediately-invoked Function Expression).
  • init can also be written as an arrow function.
  • If no other logic is performed in an arrow function before the return statement, and it returns an object literal, it can be further simplified. To return an object literal from an arrow function, wrap it in parentheses:

var myApp = (
   () => ({
       init: () => console.log('MyApp init')
   })
)();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.