Last active
December 28, 2015 19:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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