Search code examples
javascriptnode.jsprototype-programming

Javascript Singleton Class Creation in NodeJS


I am mentioning two approaches for creating the Singleton class in NodeJS express app, please help me in understanding few things about these implementations:

  • Confirm if both mean the same - I guess yes, because results in same run time output
  • Which one is preferred way of coding
  • Is there any performance difference
  • Any other better way of creating classes for Controllers and database wrappers in NodeJS Express app

Approach 1

(function (nameClass) {
    nameClass.name = 'John';
    nameClass.getName = function () {
        return nameClass.name;
    };
    nameClass.setName = function (newName) { 
        nameClass.name = newName;
    };
})(module.exports);

Approach 2

var fu = new function () {
    this.name = "John";
    this.getName = function () {
        return this.name;
    };
    this.setName = function (newName) { 
        this.name = newName;
    };
};
module.exports = fu;

Solution

  • 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.