From what I have heard, the following is a "self-calling function":
func(){}();
How is it different from the following?
func(){} func();
From what I have heard, the following is a "self-calling function":
func(){}();
How is it different from the following?
func(){} func();
Share
Improve this question
edited Sep 22, 2011 at 17:52
Tomasz Nurkiewicz
341k71 gold badges712 silver badges679 bronze badges
asked Sep 22, 2011 at 13:13
wOlVeRiNewOlVeRiNe
5751 gold badge5 silver badges21 bronze badges
0
1 Answer
Reset to default 12I assume you meant what is the difference between (I):
function(){}();
and (II):
function func(){};
func();
or even (III):
var func = function(){};
func();
All three behave the same in regard to the results, however they have different naming and scoping consequences:
I: this will not make the function available under any name, it is run once and forgotten. You can not reference it in the future
II:
func
function is created and available in the whole enclosing function, even before it is defined (hoisting)III:
func
variable is defined pointing to a function. It won't be accessible before being defined.
Note that in II and III the function is referencable via func
name and can be called again multiple times. This is not possible with self-calling function in I.