Wednesday, May 2, 2012

JavaScript Fun Part 3: Implementing A Static Class

What Do I Mean "Static Class"?

First off, a lot of my programming lexicon will be coming from a Microsoft .Net perspective, and to be quite frank, even that has evolved a lot along the way, due to the fact I am self-taught. When I say "static class" what I'm talking about is a class whose public members are accessible without creating an instance of that class.

What Is A "Non-Static Class" In JavaScript?

A instanced (non-static) class in JavaScript is the classic JavaScript function class. Created by declaring a function, then calling it along with the "new" keyword:

var Foo = function () {
   this.bar = function() {
      alert('Foo.bar() called.');
   };
};

var f = new Foo();
f.bar(); //Foo.bar() called.;

Implementing A Static Class In JavaScript

In JavaScript, a static class isn't much more than an object literal. Because objects in JavaScript are dynamic, we can augment them outside of the declaration to our hearts content, but the nature of the beast is the same: It's an object with a bunch of properties and methods on it.


var FooStatic = {
   bar: function () {
      alert('FooStatic.bar() called.');
   }
};

FooStatic.bar(); //FooStatic.bar() called.

Implementing a Static Class With Private Members

The first thing many people will notice about this pattern is the lack of privacy of it's members. No members declared on FooStatic in the manner will ever be hidden from other code. But Closure, being awesome, gives us a clever way around that:

var FooStatic = (function() {
    var barPrivate = function() {
        alert('FooStatic.barPrivate() called.');
    };
    return {
        bar: function () {
           barPrivate();
        }
    }
})();

FooStatic.bar(); //FooStatic.barPrivate() called.

What the... ?

So how did this work? Using the magic of Closure, we created a container function that contained the private member we needed, in this case the variable holding the function reference to "barPrivate", then we had that container function return an object literal that had the method "bar" on it that makes a call to "barPrivate", which it has access to because it's in the same closure. We then immediately call that container function, putting its result in FooStatic. Easy peasy, if a little tricky.

This is just one of many fun uses of Closure, which I've learned to be the keys to the kingdom when it comes to JavaScript's full potential.

No comments:

Post a Comment

This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)