Search This Blog

Wednesday, August 3, 2011

Naming convention for modules with constructors in Nodejs

Modules that require instantiation through a class function have the first letter in their name capitalised, in the same fashion as the class function name itself.
This  tells the user that they should use the new keyword when calling the module, before gaining access to its methods.

MyModule.js

function MyClassFunction(param) {
   var self = this;
   // do stuff
}


module.exports = MyClassFunction;

usage:

var myObject = new (require('MyModule'))(param);


This naming convention focuses on usage rather than direct implementation. As such
Modules that have private class functions, called by static methods or wrapper functions, should begin with a lower case letter in their name.


myModule.js




function MyClassFunction(message) {
   var self = this;
   console.log('Instantiated private obj.');
};


MyClassFunction.staticMethod = function() {
   var message = 'Called from static method';
   return new MyClassFunction(message);
};


module.exports = {
   myMethod: MyClassFunction.staticMethod
};



usage:
require('./myModule').myMethod();

No comments:

Post a Comment