Skip to content

Instantly share code, notes, and snippets.

@hellogerard
Last active March 8, 2017 18:26
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 hellogerard/461785f86b445abfb650cbc216aea909 to your computer and use it in GitHub Desktop.
Save hellogerard/461785f86b445abfb650cbc216aea909 to your computer and use it in GitHub Desktop.
Functional JS approach to classic Animals OO example - https://jsfiddle.net/wjkLagf8/1/
const animal = {
type: 'animal',
talk() {
alert('Hello, world!');
},
move() {
alert(`${this.name} the ${this.type} moved forward`);
}
};
const createAnimal = (name = 'george') =>
Object.assign(Object.create(animal), {
name
});
const cow = Object.assign(createAnimal(), {
type: 'cow',
talk() {
alert('moooooo');
}
});
const createCow = (name = 'frank') =>
Object.assign(Object.create(cow), {
name
});
const dog = Object.assign(createAnimal(), {
type: 'dog',
talk() {
alert('woof woof');
}
});
const createDog = (name = 'bobby') =>
Object.assign(Object.create(dog), {
name
});
const jason = createAnimal('jason');
const mary = createCow('mary');
const justin = createDog('justin');
jason.talk();
mary.talk();
justin.talk();
jason.move();
mary.move();
justin.move();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment