Skip to content

Instantly share code, notes, and snippets.

@alvarezmauro
Last active May 8, 2018 02:46
Show Gist options
  • Save alvarezmauro/f2abce67b96304450a7dd30b06ef6c64 to your computer and use it in GitHub Desktop.
Save alvarezmauro/f2abce67b96304450a7dd30b06ef6c64 to your computer and use it in GitHub Desktop.
JS Design patterns - Inheritance - Explicit prototype declaration, Object.create, method factory
var Animal = {
create(type){
var animal = Object.create(Animal.prototype);
animal.type = type;
return animal;
},
isAnimal(obj, type){
if(!Animal.prototype.isPrototypeOf(obj)){
return false;
}
return type ? obj.type === type : true;
},
prototype: {}
};
var Dog = {
create(name, breed){
var dog = Object.create(Dog.prototype);
Object.assign(dog, Animal.create("dog"));
dog.name = name;
dog.breed = breed;
return dog;
},
isDog(obj){
return Animal.isAnimal(obj, "dog");
},
prototype: {
bark(){
console.log("ruff, ruff");
},
print(){
console.log("The dog " + this.name + " is a " + this.breed);
}
}
};
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment