Skip to content

Instantly share code, notes, and snippets.

@shama
Last active August 29, 2015 13:57
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shama/9884884 to your computer and use it in GitHub Desktop.
Save shama/9884884 to your computer and use it in GitHub Desktop.
My favorite node.js module pattern
function Animal(name) {
if (!(this instanceof Animal)) return new Animal(name);
this.name = name || 'unknown';
}
module.exports = Animal;
Animal.prototype.feed = function(food) {
food = food || 'food';
return 'Fed ' + this.name + ' some ' + food;
};
/* Which later can be consumed by using a function... */
var createAnimal = require('animal');
var bear = createAnimal('bear');
bear.feed('fish');
// Fed bear some fish
/* Or using `new`... */
var Animal = require('animal');
var lion = new Animal('lion');
lion.feed('antelope'); // Fed lion some antelope
/* Or more succinctly... */
require('animal')('rabbit').feed('carrots'); // Fed rabbit some carrots
/* Or even with inheritance... */
var Animal = require('animal');
var inherits = require('inherits');
function Tiger() {
if (!(this instanceof Tiger)) return new Tiger();
this.name = 'tiger';
}
inherits(Tiger, Animal);
(new Tiger()).feed('meat'); // Fed tiger some meat
/* ALL FROM THE SAME MODULE PATTERN :D */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment