mandag den 29. april 2013

Javascript "static" class - make javascript code more readable

I usually use static classes for my C# helper-functions, when there're no properties to expose, nor any need to inherit from them. So this increases code readability. Javascript, however, doesn't have that feature, so how to immitate it? I usually do the below:

// declare object - recall that 'function' is an object in javascript
var WebServiceFunctions = function() {

// declare method on the object
WebServiceFunctions.webServiceMethod = function (parameter1, parameter2) {
// method code here

// return value if any
return xyz;

With the above code, I call my helper-method in my code like this:

var resultFromCall = WebServiceFunctions.webServiceMethod("foo","bar");

This has the odour of a static class. Of course behind the scene the "var WebServiceFunctions = function() {}" declaration signifies the creation of an object ("function" is an object in javascript), but I find that given the generic name - 'WebServiceFunctions' - my mind abstracts from this.

The javascript increases in readability, which may be an issue with a multitude of referenced javascript files.

There's a slightly better way, though. If the helper-functions are so generic in nature that they're applicable to many different purposes, they may be used in many different files. As such, the above will declare the "WebServiceFunctions"-object with every import of the javascript file. Better would be to check beforehand if the object has already been created, in which case there's no need to create it again:

(function () {
    this.WebServiceFunctions = this.WebServiceFunctions || {};

    var ns = this.WebServiceFunctions;

    ns.getMobilityPeriodId = function (serviceUrl) {
             // function code here


The above this.WebServiceFunctions = this.WebServiceFunctions || {}; is a conditional that checks if this.WebServiceFunctions has any value, in which case the already created object is returned, or - represented by the two pipes '||' - a new object is created. var ns is merely a reference, to avoid having to write 'this.WebServiceFunctions' repeatedly.

So that's a way to reference javascript in a 'namespace' sort of way. I find the above helps me keep my references handy and maintain the readability of my code, especially as a project starts to become clotted with javascript. If you wish to go depper into the subject matter, the above is what is known as the Javascript Module Pattern.

Ingen kommentarer:

Send en kommentar