Last active
August 29, 2015 13:57
-
-
Save shama/9884884 to your computer and use it in GitHub Desktop.
My favorite node.js module pattern
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
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