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.
var WebServiceFunctions = function() {
}
WebServiceFunctions.webServiceMethod = function (parameter1, parameter2) {
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 J
avascript), 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) {
}
})();
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.