Вопрос

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?

Это было полезно?

Решение

Since the result of your SEAF (better named IEFE) 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 {…};
})();

Другие советы

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.

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')
   })
)();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top