I am mentioning two approaches for creating the Singleton class in NodeJS express app, please help me in understanding few things about these implementations:
(function (nameClass) {
nameClass.name = 'John';
nameClass.getName = function () {
return nameClass.name;
};
nameClass.setName = function (newName) {
nameClass.name = newName;
};
})(module.exports);
var fu = new function () {
this.name = "John";
this.getName = function () {
return this.name;
};
this.setName = function (newName) {
this.name = newName;
};
};
module.exports = fu;
Singleton is class which has only one instance. Javascript doesn't have classes. Of course, they can be emulated easily with constructors and prototypes and on top of that you can emulate singleton, but what for? You can create instances directly.
If you remove the parts of your code that make no sense both approaches will become the same:
exports.name = "John";
exports.getName = function () {
return this.name;
};
exports.setName = function (newName) {
this.name = newName;
};
You can also make name
"private":
var name = "John";
exports.getName = function () {
return name;
};
exports.setName = function (newName) {
name = newName;
};
That's the best "singleton" in node.js.