Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active December 10, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/4355516 to your computer and use it in GitHub Desktop.
Save cowboy/4355516 to your computer and use it in GitHub Desktop.
JavaScript: possible Node.js Ctor/.create export pattern
function Thing(prop) {
this.prop = prop;
}
Thing.prototype.toString = function() {
return "My prop is: " + this.prop;
};
// Export constructor and a .create method
function exportify(Ctor) {
module.exports[Ctor.name] = Ctor;
module.exports.create = function() {
var instance = Object.create(Ctor.prototype);
Ctor.apply(instance, arguments);
return instance;
};
}
exportify(Thing);
// Option one:
var Thing1 = require("./thing").Thing;
var thing1 = new Thing1("foo");
String(thing1) // "My prop is: foo"
// Option two:
var Thing2 = require("./thing");
var thing2 = Thing2.create("bar");
String(thing2) // "My prop is: bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment