Skip to content

Instantly share code, notes, and snippets.

@fraserxu
Forked from shama/favorite_module_pattern.js
Created March 31, 2014 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fraserxu/9886391 to your computer and use it in GitHub Desktop.
Save fraserxu/9886391 to your computer and use it in GitHub Desktop.
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