Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How things are done everywhere. Versus how I want them to be done.
// tired of this extension pattern
var Cow = AnimalFactory({
getVoice: function() { return 'moo'; }),
numLegs: 4,
name: 'Cow',
})
// propose this one instead
var MutantCow = AnimalFactory.extend()
.getVoice(function() { return 'moo'; })
.numLegs(5)
.name('Cow');
var Crow = AnimalFactory.extend()
.getvoice(function() { return 'CAWW!'; } // no method error
.numlegs(2) // no method error
// what other things can I configure?
// the configuration object gives me a good hint
Object.keys(AnimalFactory.configure())
function AnimalFactory() {
var classConfig = {};
var = {};
var _classAttributes = {};
//downside: lots of boilerplate for the owner
classConfig.getVoice = function(voiceFunction) {
_classAttributes.getVoice = voiceFunction;
return classConfig;
};
classConfig.numLegs = function(numLegs) {
_classAttributes.numLegs = numLegs;
return classConfig;
};
classConfig.name = function(name) {
_classAttributes.name = name;
return classConfig;
};
this.extend = function() {
return (new AnimalFactory())._configure();
};
this._configure = function() {
return classConfig;
};
this.instantiate = function() {
var instance = {};
instance.speak = function() {
alert(_classAttributes.getVoice());
};
instance.walk = function() {
alert([
_classAttributes.name,
"is walking with its",
_classAttributes.numLegs,
"legs"
].join(' '));
};
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment