Skip to content

Instantly share code, notes, and snippets.

@dvonlehman
Last active December 28, 2015 19:09
Show Gist options
  • Save dvonlehman/7548395 to your computer and use it in GitHub Desktop.
Save dvonlehman/7548395 to your computer and use it in GitHub Desktop.
Template for exporting a class in a node module based on Crockford: http://javascript.crockford.com/private.html
var util = require("util"),
BaseThing = require("./base_thing");
// Constructor function
var Thing = module.exports = function(attrs){
this.attrs = attrs;
// Priveleged method can be invoked by public methods
this.privelegedMethod = function() {
}
}
// Inheritance
util.inherits(Thing, BaseThing);
// Optionally dynamic assignment of properties
Object.defineProperty(Thing.prototype, "name", {
get: function () { return this.attrs.name; }
});
// Public methods
Thing.prototype.doSomething = function (arg1, arg2) {
// Access constructor arguments with this
this.attrs
// Invoke priveleged methods
this.privelegedMethod();
};
// Override toJSON, return the thing that should be serialized with JSON.stringify
Thing.prototype.toJSON = function() {
return this.attrs;
};
module.exports = Thing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment