How to call a self executing function in JavaScript?

javascript

Solution

If your function doesn't rely on a return value, you can do this...

var foo = (function bar() {
   alert('hello');
   return bar;
})();   // hello

foo();  // hello

This uses the local reference `bar` in the named function expression to return the function to the outer `foo` variable.

Or even if it does, you could make the return value conditional...

var foo = (function bar() {
   alert('hello');
   return foo ? "some other value" : bar;
})();   // hello

alert( foo() );  // hello --- some other value

or just manually assign to the variable instead of returning...

var foo; 
(function bar() {
   alert('hello');
   foo = bar;
})();   // hello

foo();  // hello

As noted by @RobG, some versions of IE will leak the identifier into the enclosing variable scope. That identifier will reference a duplicate of the function you created. To make your NFE IE-safe(r), you can nullify that reference.

bar = null;

Just be aware that the identifier will still shadow an identifier with the same name up the scope chain. Nullifying won't help that, and local variables can not be deleted, so choose the NFE name wisely.

Problem

When I have some code I need to execute more than once I wrap it up in a function so I don't have to repeat myself. Sometimes in addition there's a need to execute this code initially on page load. Right now I do it this way: ``` function foo() { alert('hello'); } foo(); ``` I would rather do it this way: ``` (function foo() { alert('hello'); })(); ``` Problem is, this will only execute on page load but if I try to call it subsequent times using `foo()` it won't work. I'm guessing this is a scope issue but is there any way to get self executing functions to work upon getting called later?

Original source

Related problems