0

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;
Louis
  • 146,715
  • 28
  • 274
  • 320
Manoj Aggarwal
  • 317
  • 2
  • 14
  • The second one actually is not a singleton. I think that makes the other question irrelevant. – Bergi Oct 14 '14 at 20:53
  • Notice that since JS is not class-based, but allows object instantiation without any class involved, the term "singleton class" is rather inappropriate for such a standalone object ("class" means "instantiable", which it is not). It's just a *module*. – Bergi Oct 14 '14 at 20:56

2 Answers2

2

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.

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
-2

i prefer second approach, but i think singleton class is a bad design pattern - it is hard to unit test.

it is worth notice, that nodejs modules are singletons by themselves (because they are cached when they are required) - https://gist.github.com/vodolaz095/6201232

vodolaz095
  • 6,680
  • 4
  • 27
  • 42