Created
December 5, 2015 21:46
-
-
Save spacious/d771d68bfd395c1c3056 to your computer and use it in GitHub Desktop.
JS prototype inheritance pattern examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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