February 15, 2011

Static variables in JavaScript - continued

Since I had some great reactions on the first part of this post I want to give an overview of two other ways to fake static variable behaviour in JavaScript.

As Polaretto mentioned in his comments it might be more clever to initialize the static variable outside the function instead of checking whether it was already initialized everytime the function executes.

That means my old snippet
var myFunction = function () {
    if (typeof myFunction.myStaticVar === 'undefined') {
        myFunction.myStaticVar = 0;
    }
    alert(myFunction.myStaticVar);
    myFunction.myStaticVar += 1;
};
Now becomes
var myFunction = function () {
    alert(myFunction.myStaticVar);
    myFunction.myStaticVar += 1;
};
myFunction.myStaticVar = 0;
This is far more efficient and easier to read. So thanks to Polaretto for the advice!

Another approach would be the use of a closure. We just create a new function that has the static variable in it's scope.

Let's see how this will look like:
var myFunction = (function () {
    var myStaticVar = 0;
    return function () {
        alert(myStaticVar);
        myStaticVar += 1;
    };
})();
Personally I prefer the first solution. The last one is perfectly fine and working correctly but a bit tougher to read.

No comments:

Post a Comment