Classy JavaScript - Best Practices

11. February 2010 13:26

Okay, so you really want to be able to have some of your JavaScript methods to have access to a variable that is private, but maintains state between calls. The first piece of knowledge, is that you can have the contents of a function execute itself at runtime.

(function(){ /*Your actions here*/ })();

This is a very common method of defining complex classes and libraries, that can have their own variables or methods that aren't otherwise available to the object model outside this closure. When you utilize "this" within the function's closure it will be default to the global object, which in the Browser DOM is "window".

(function(){
    this.test = "Test Value";
})();
alert(test); //alerts "Test Value"

Usually when creating libraries in JavaScript it's a good idea to create namespaces for your library. Below I am going to use a classic example for defining a namespace of My.Namespace. There are helper methods out there that will walk a chain from a literal string of "My.Namespace", but I'm showing it in raw script.

if (typeof My == 'undefined')
  My = {};
if (typeof My.Namespace == 'undefined')
  My.Namespace = {};

By combining the above method, and using the Function.prototype.call method on your anonymous function, you can call the function with "this" set to your namespace. I'll be implementing a class called "SomeClass" within "My.Namespace" below. I'll also be showing how to create private static members and methods, allong with public static methods, and instance methods.

//begin private closure
(function(){

    //this is a private static member that is only available in this closure
    var instances = 0;

    //this is a private static method that can be used internally
    function _incrementInstances() {
        instances++;
    }

    //Define SomeClass (js uses functions as class constructors, utilized with the "new" keyword)
    this.SomeClass = function(options) {
        //if the function is called directly, return an instance of SomeClass
        if (!(this instanceOf SomeClass))
            return new SomeClass(options);

        //call static method
        _doSomething();

        //handle the options initialization here
    }

    //create a public static method for SomeClass
    this.SomeClass.getInstanceCount = function() {
        return instances; //returns the private static member value
    }

    //create an instance method for SomeClass
    this.SomeClass.prototype.doSomething = function() {
      /*Do Something Here*/
    }

//end private closure then run the closure, localized to My.Namespace
}).call(My.Namespace);

The above is an example of best practices for defining a Class within a given namespace. From here, you can instantiate an instance of "My.NameSpace.SomeClass" and utilize the public methods exposed.

//instantiate a SomeClass instance
var sc = new My.Namespace.SomeClass({/* options go here */});

//call SomeClass as a function, which will return an instance
//  defined above via "(!(this instanceOf SomeClass))"
var sc = My.Namespace.SomeClass({/* options */});

//view the instance count, which uses a public static method
//  to return a private static member.
alert(My.Namespace.SomeClass.getInstanceCoun());

From here, you may be thinking to yourself, that's a lot of typing. This is where aliasing can come in handy, in this example inside a closure of course.

(function(){
    //alias My.NameSpace
    var m = My.NameSpace

    //bad form assigning onload internally,
    //  but that'll be for another post on event binding
    //  Also, we could use "this.onload" but using window directly is more obvious here.
    window.onload = function() {
        //attach an instance of My.NameSpace.SomeClass instance to window.
        window.sc = new m.SomeClass({}); //no long namespace name here :)
    }

})();

Hopefully this post will be helpful in utilizing some privacy with your classes, and using namespaces to prevent naming collisions with other classes, and libraries.

Comments

2/13/2010 2:31:14 PM #

Livingston Samuel

the first code snippet should be either,

(function(){ /*Your actions here*/ }());

or

(function(){ /*Your actions here*/ })();

Livingston Samuel India |

2/15/2010 3:37:58 PM #

tracker1

@sam, thanks corrected above.

tracker1 United States |

Comments are closed

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.