Reputation: 1734
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?
Upvotes: 3
Views: 8296
Reputation: 665185
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 {…};
})();
Upvotes: 3
Reputation: 1061
var myApp = (() => {
return {
init: () => console.log('MyApp init')
};
})();
myApp.init();
myApp
is set to the result of an IIFE (Immediately-invoked Function Expression).init
can also be written as an arrow function.var myApp = (
() => ({
init: () => console.log('MyApp init')
})
)();
Upvotes: 0
Reputation: 8620
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.
Upvotes: 1