Sometimes when I need a static variable I use and immediately invoked function expression (IIFE) – example1.
(function(){
var private_statik = 'hi',
publik = {};
return publik;
}())
other times I just tack them on as properties to the function which needs them as such – example2.
function foo () {
}
foo.statik = 'hello';
Example1 is good b.c. I get the benefit of encapsulation ( privacy ). Example 2 is good b.c. it is simple and there is no overhead for the self-execution.
Are there any other things to consider?
The case specific I have is a page changer – sFlipPage(). I want to cache all the DOM elements in a static location so they are available on each call and I don’t have to pull them from the DOM each time I call the function.
Thanks!
The primary difference is privacy and execution order. With an IIFE you can make your static variables private. With a plain function you can not. In order to encourage good OO design ( encapsulation ) I would suggest using an IIFE by default.
The trade-off is that an IIFE is invoked immediately not just when you need that particular object.