Search code examples
javascriptinheritanceprototype

Problems inheriting properties from a supertype


I'm creating an Animal supertype constructor which has a method that should be available for all 'bird' and 'cat' objects.

  • How should I add this prototype to make sure I don't overwrite the subtypes' prototype?
  • Can I use a subtype prototype's variable in the supertype prototype?

Example

function Animal() { }

Animal.prototype = {
  constructor: Animal,
  say: function(sound) {
    console.log(`${sound}`);
  }
};

function Cat(name) {
  this.name=name
 }
function Bird(name) {
  this.name=name
 }
Cat.prototype = {
  constructor:Bird,
  sound:'meow'
}
Bird.prototype = {
  constructor:Bird,
  sound:'Bach Op1 D minor'
}

Cat.prototype = Object.create(Animal.prototype)
Bird.prototype = Object.create(Animal.prototype)
//is this overwriting the prototype already set?
let myCat = new Cat("rupert")
console.log(myCat.name, myCat.say(), Cat.prototype)


Solution

  • You can use Object.assign to inherit from Animal's prototype but also be able to add your own fields and methods. Also, you need to use this.sound to access the property of the instance itself.

    Animal.prototype = {
      constructor: Animal,
      say: function() {
        console.log(`${this.sound}`);
      }
    };
    //...
    Cat.prototype = Object.assign(Object.create(Animal.prototype), {
      constructor:Bird,
      sound:'meow'
    });
    Bird.prototype = Object.assign(Object.create(Animal.prototype),{
      constructor:Bird,
      sound:'Bach Op1 D minor'
    });
    

    Demo:

    function Animal() { }
    
    Animal.prototype = {
      constructor: Animal,
      say: function() {
        console.log(`${this.sound}`);
      }
    };
    
    function Cat(name) {
      this.name=name
     }
    function Bird(name) {
      this.name=name
     }
    Cat.prototype = Object.assign(Object.create(Animal.prototype), {
      constructor:Bird,
      sound:'meow'
    });
    Bird.prototype = Object.assign(Object.create(Animal.prototype),{
      constructor:Bird,
      sound:'Bach Op1 D minor'
    });
    //is this overwriting the prototype already set?
    let myCat = new Cat("rupert")
    console.log(myCat.name, myCat.say(), Cat.prototype)