Declaring Singleton with public and private members in Javascript
I just had my javascript venture reviewed by my buddy Kenneth Wrang, who I consider a master of Javascript (eventhough he wouldn't admit it). I learned a few valuable things about this language, and how it differ to other languages like C#.
The first one I want to share here is how to declare singleton in Javascript, and how I could create private/public members. They may not be obvious since Javascript doesn't have special keywords for class, public and private modifiers.
var aSingleton = (function() {
// NOTE 1: these are the private members
// they will not be accessible from outside the scope of this 'function'
var privateMember = "test";
var someCollection = [];
// NOTE 2: this is a private class within the singleton
// var1 and var2 are the dependencies of the class
// similar to a constructor in other language like C#
function aPrivateClass(var1, var2) {
// NOTE 3: state is also a private member
var state = "state";
return {
// NOTE 4: public member to the private class
anInnerFunction: function() {
$(document.body).append("<p>" + state + "</p>");
}
};
}
return {
// NOTE 5: these are the public members
aPublicFunction: function() {
// NOTE 6: private class will be accessible from the public methods
// thanks to Closure
someCollection.push(aPrivateClass("dependency1", "dependency2"));
// NOTE 7: eventhough the private members of the private class cannot
// be accessed, the public members of the private class are.
someCollection[0].anInnerFunction();
}
};
})();
// NOTE 8: from this point on, we have our singleton created
// with only the public members exposed.
aSingleton.aPublicFunction();
Most of the notes are already done in-line, so hopefully the example will be self explanatory. However I'd like to point out something that may not be obvious:
Private members are all members before the return statement
for e.g
Note 1, Note 2 in the scope of aSingleton, and
Note 3 in the scope of aPrivateClass.
Public members are all the members inside the return statement
for e.g
Note 5 in the scope of aSingleton, and
Note 4 in the scope of aPrivateClass.