Skip to content

Instantly share code, notes, and snippets.

Created April 16, 2015 18:17
Show Gist options
  • Save anonymous/5a57155871d672882922 to your computer and use it in GitHub Desktop.
Save anonymous/5a57155871d672882922 to your computer and use it in GitHub Desktop.
What is the right way to do inheritance with Object.create() ?
function Animal(genus, species) {
var animal = Object.create(Animal.prototype);
animal.genus = genus;
animal.species = species;
return animal;
}
function Dog(species) {
// Clear the following line fails, since Animal explicitly Object.create()s an Animal instance
// How do I properly re-use the Animal constructor?
return Animal.prototype.constructor.call(this, 'Canis', species);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var dog = Dog('lupus');
console.log(dog); // {genus: 'Canis', species: 'lupus'}, as expected
console.log(dog instanceof Dog); // False, but it should be true
console.log(dog instanceof Animal); // True, as expected
function Animal(genus, species) {
var animal = Object.create(Animal.prototype);
animal.init(genus, species);
return animal;
}
Animal.prototype.init = function(genus, species) {
this.genus = genus;
this.species = species;
}
function Dog(species) {
var dog = Object.create(Dog.prototype);
dog.init('Canis', species);
return dog;
}
Dog.prototype = Object.create(Animal.prototype);
var dog = Dog('lupus');
console.log(dog); // {genus: 'Canis', species: 'lupus'}, as expected
console.log(dog instanceof Dog); // True, as expected
console.log(dog instanceof Animal); // True, as expected
function Animal(genus, species) {
var animal = Object.create(Animal.prototype);
animal.genus = genus;
animal.species = species;
return animal;
}
function Dog(species) {
var dog = Animal.prototype.constructor.call(this, 'Canis', species);
dog.__proto__ = Object.create(Dog.prototype);
return dog;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var dog = Dog('lupus');
console.log(dog); // {genus: 'Canis', species: 'lupus'}, as expected
console.log(dog instanceof Dog); // True, as expected
console.log(dog instanceof Animal); // True, as expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment