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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Iain
  • 1,724
  • 6
  • 23
  • 39
  • 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. – Mike Edwards Oct 17 '13 at 21:11
  • 2
    [Your code works just fine](http://jsfiddle.net/m5QeQ/) assuming you catch the return values. – zzzzBov Oct 17 '13 at 21:11
  • As zzzzBov points out, it works just fine if you put `var someName = (theClosureExecution)` – Mike Edwards Oct 17 '13 at 21:12
  • What is *"[SEAF](https://en.wikipedia.org/wiki/SEAF)"*? *"[IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)"*? – Peter Mortensen Apr 16 '23 at 17:37
  • OK, SEAF is probably [self-executing anonymous function](https://stackoverflow.com/questions/14322708). – Peter Mortensen Apr 16 '23 at 17:41

3 Answers3

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 {…};
})();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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? – Iain Oct 19 '13 at 13:01
  • 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. – Bergi Oct 19 '13 at 20:27
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.

Katana314
  • 8,429
  • 2
  • 28
  • 36
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')
   })
)();
Wojciech K
  • 952
  • 7
  • 16