Reputation: 2664
I am wondering what the difference is between this:
(function(msg) {
alert(msg);
}('Hi'));
and this:
alert('Hi');
Because when you use an anonymous function, you can't run it twice, right? You can't do this:
(function(msg) {
alert(msg);
}('Hi')('Goodbye'));
So what's the point of an anonymous function?
This:
(function(msg) {
alert(msg);
}('Hi'));
gets the same output as this:
alert('Hi');
Could someone tell me what the difference is?
Upvotes: 0
Views: 86
Reputation: 144
the anonymous function is when you declare a function without name i.e
function(){
...
}
Your example is an inmediate function, here you can hide properties and functionality (using closures, this is complex I recommend you The secrets of JS Ninja, but is a intermediate lvl book.), so you can use this when use the module pattern:
(function(msg) {
alert(msg);
}('Hi'));
BTW this is a good resource about patterns in JS: http://addyosmani.com/resources/essentialjsdesignpatterns/book/
Upvotes: 1
Reputation: 10627
Your example shows an Anonymous Function that is self-executing. The self-executing Function closes off scope, so you can do things like this:
var count = (function(){
var c = 0;
return function(){
return c++;
}
})();
console.log(count()); console.log(count());
In your first example nothing different will occur. An Anonymous function, just has no name, so this:
document.getElementById('whatever').addEventListener('click', function(){alert('wow')});
and
function wow(){
alert('wow');
}
document.getElementById('whatever').addEventListener('click', wow);
do the same thing.
Upvotes: 2
Reputation: 700212
The main difference is that it has its own scope. Example:
(function(msg) {
var x = msg; // local variable in the scope
alert(x);
}('Hi'));
// the variable x doesn't exist out here
That is useful when you for example create a function in the scope, and expose it outside. The function still has access to the scope even when executed outside it. That way the function can keep a state, without exposing the state globally:
var f = (function(msg) {
var cnt = 1;
return function(){
alert(msg + ' ' + cnt);
cnt++;
};
}('Hi'));
f(); // shows "Hi 1"
f(); // shows "Hi 2"
Upvotes: 3