Skip to content

Instantly share code, notes, and snippets.

@dannyfritz
Last active July 4, 2016 03:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dannyfritz/3973e50697bcc9888061 to your computer and use it in GitHub Desktop.
Save dannyfritz/3973e50697bcc9888061 to your computer and use it in GitHub Desktop.
A Duck, an Alligator, and a Goat
function newAlligator () {
var alligator = {
name: 'alligator',
word: 'grrr'
};
extend(alligator, withAnimal);
extend(alligator, withWalking);
extend(alligator, withSwimming);
return alligator;
}
function newDuck () {
var duck = {
name: 'duck',
word: 'quack'
};
extend(duck, withAnimal);
extend(duck, withWalking);
extend(duck, withFlying);
extend(duck, withSwimming);
return duck;
}
function newGoat () {
var goat = {
name: 'goat',
word: 'baa'
};
extend(goat, withAnimal);
extend(goat, withWalking);
return goat;
}
var alligator = newAlligator();
alligator.talk();
alligator.swim();
alligator.walk();
var duck = newDuck();
duck.talk();
duck.fly();
duck.walk();
var goat = newGoat();
goat.talk();
goat.walk();
function extend (target, source) {
Object.keys(source).forEach(function (key) {
if (typeof target[key] !== 'undefined') {
return;
}
target[key] = source[key];
});
}
var withAnimal = {
name: 'name',
word: 'word',
talk: function () {
console.log(this.name + ' says ' + this.word);
}
};
var withFlying = {
fly: function () {
console.log('flap flap');
}
};
var withSwimming = {
swim: function () {
console.log('splish splash');
}
};
var withWalking = {
walk: function () {
console.log('stomp stomp');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment