How to call a self executing function in JavaScript? -


when have code need execute more once wrap in function don't have repeat myself. in addition there's need execute code on page load. right way:

function foo() {    alert('hello'); }  foo(); 

i rather way:

(function foo() {    alert('hello'); })(); 

problem is, execute on page load if try call subsequent times using foo() won't work.

i'm guessing scope issue there way self executing functions work upon getting called later?

if function doesn't rely on return value, can this...

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

this uses local reference bar in named function expression return function outer foo variable.


or if does, make return value conditional...

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

or manually assign variable instead of returning...

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

as noted @robg, versions of ie leak identifier enclosing variable scope. identifier reference duplicate of function created. make nfe ie-safe(r), can nullify reference.

bar = null; 

just aware identifier still shadow identifier same name scope chain. nullifying won't that, , local variables can not deleted, choose nfe name wisely.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -