-1

I am working on a nodejs application that requires access to some network resources (such as cache services, DB, and so forth). In order to access these resources, I have written a module (imported via require that the nodejs app uses to access these network resources.

The dilemma I am facing is the following: should this modules be implemented using a constructor patter, or an object literal pattern?

Using Constructor

By constructor, I mean something like this:

function databaseHelper = function(){
    *//public properties go here*
}
databaseHelper.prototype.methodA = function methodA() {}
...

so that nodejs modules that require this module will consume it like this:

var db = require ('dbhelper.js');
var dbhelper = new db();
dbhelper.methodA();

Using object literal

The other alternative is to implement the module as this:

function databaseHelper = function databaseHelper(){
    return {
        propertyA: '',
        propertyB: 100,
        methodA: function methodA(){}
    }
}

so that modules that utilize this database helper will only instatiate a variable with require' and will not use the 'new' keyword anywhere.

What's the best practice for node modules in this regards, particularly for modules that will be frequently utilized by other modules for network operations? Is the constructor/prototyping approach recommended (and why), or should we refrain from using the pattern and instead build functions that return object literals with properties and functions?

Luis Delgado
  • 3,644
  • 4
  • 34
  • 54
  • I'm not sure how you expect objects created by literals to have any advantages over those instantiated with `new`? – Bergi Dec 15 '14 at 22:24

1 Answers1

0

In your case, I would take the first approach, mainly for one reason: if you define a method in an object literal, then every instance created through databaseHelper() might end up having its own copy of the function. This is of course less memory-efficient. If you define methods on the prototype, then there's only one copy of the function that just is bound to a different this reference.

Jacob
  • 77,566
  • 24
  • 149
  • 228