Skip to content

Instantly share code, notes, and snippets.

@spacious
Created December 5, 2015 21:46
Show Gist options
  • Save spacious/d771d68bfd395c1c3056 to your computer and use it in GitHub Desktop.
Save spacious/d771d68bfd395c1c3056 to your computer and use it in GitHub Desktop.
JS prototype inheritance pattern examples
// https://medium.com/@PitaJ/javascript-inheritance-patterns-179d8f6c143c#.36nqv16pb
// Object.create, top-level factory, prototype post-declaration
function Animal(type){
var animal = Object.create(Animal.prototype);
animal.type = type;
return animal;
}
Animal.isAnimal = function(obj, type){
if(!Animal.prototype.isPrototypeOf(obj)){
return false;
}
return type ? obj.type === type : true;
};
Animal.prototype = {};
function Dog(name, breed){
var dog = Object.create(Dog.prototype);
Object.assign(dog, Animal("dog"));
dog.name = name;
dog.breed = breed;
return dog;
}
Dog.isDog = function(obj){
return Animal.isAnimal(obj, "dog");
};
Dog.prototype = {
bark(){
console.log("ruff, ruff");
},
print(){
console.log("The dog " + this.name + " is a " + this.breed);
}
};
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
// https://medium.com/@PitaJ/javascript-inheritance-patterns-179d8f6c143c#.36nqv16pb
// 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