Inheritance with factory method/class pattern
inheritance, javascript
Solution
You would use `Object.create`:
const animal = () => ({
talk: function() {
console.log(this.sound);
}
});
const dog = () => Object.create(animal(), {
sound: {
value: "woof"
}
});
// or...
const dog2 = () => {
var someDog = Object.create(animal());
someDog.sound = "woof";
return someDog;
};
var someDog = dog();
someDog.talk();
var someDog2 = dog2();
someDog2.talk();
BTW, my opinion is that you should go with ES2015+ class/inheritance and leave the use of custom factories and `Object.create` for corner cases where you really need them:
class Animal {
talk() {
return console.log(this.sound);
}
}
class Dog extends Animal {
constructor() {
super();
this.sound = "woof";
}
}
var dog = new Dog();
dog.talk();
Problem
I was reading about different methods of object creation in JavaScript instead of using `new` and ES6-classes. One method is using the factory method/factory class pattern (taken from https://medium.com/humans-create-software/factory-functions-in-javascript-video-d38e49802555): ``` const dog = () => { const sound = 'woof' return { talk: () => console.log(sound) } } const sniffles = dog() sniffles.talk() // Outputs: "woof" ``` How would I implement a class like `Animal` or rather another factory funtion which my dog function can "inherit" from? Would I pass the animal object to the dog function and set the prototype of the object being returned to the passed animal object?