Is there a preferred way of doing what I describe here. I want to namespace my JavaScript code and use the Singleton Pattern so that only one instance of my JavaScript app exists.
I have seen two approaches to this in JavaScript. One which simply returns and object literal, and another which uses the Revealing Module Pattern. If all I want is a singleton object (not caring about enforcing faux public/private methods and properties) is returning an object literal the way to go?
// Approach 1
var AppOne = (function(){
return {
Util: {
init: function() {
$("body").append("<strong>AppOne.Util initiliased</strong><br>");
}
},
Ajax: {
init: function(){
$("body").append("<strong>AppOne.Ajax initialised</strong><br>");
}
}
};
})();
// Approach 2
var AppTwo = (function(){
var Util = function() {
return {
init: function() {
$("body").append("<strong>AppTwo.Util initialised</strong><br>");
}
};
}();
var Ajax = function() {
return {
init: function() {
$("body").append("<strong>AppTwo.Ajax initialised</strong><br>");
}
};
}();
return {
Util: Util,
Ajax: Ajax
};
})();
AppOne.Util.init();
AppOne.Ajax.init();
AppTwo.Util.init();
AppTwo.Ajax.init();