Wednesday, July 15, 2020

Simple inheritance

function Animal(theName) {
  this.animalName = theName;
  console.log('The animal constructor is called, the name is ' + theName);
}


Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};

function Dog(theName) { 
  console.log('dog constructor called');
  Animal.call(this, theName)

}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log(`Dog named ${this.animalName} is barking`);
}


// Only change code below this line


const beagle = new Dog('spot');
console.log(Dog.prototype.isPrototypeOf(beagle));
console.log(Animal.prototype.isPrototypeOf(Dog.prototype));
console.log(Animal.prototype.isPrototypeOf(beagle));
console.log(beagle.constructor === Dog);
console.log(beagle.constructor === Animal);

beagle.bark();

dog constructor called
The animal constructor is called, the name is spot
true
true
true
true
false
Dog named spot is barking

No comments:

Post a Comment