DEV Community

Randy Rivera
Randy Rivera

Posted on

Overriding Inherited Methods

  • In previous posts, you learned that an object can inherit its behavior (methods) from another object by referencing its prototype object:
ChildObject.prototype = Object.create(ParentObject.prototype);
Enter fullscreen mode Exit fullscreen mode
  • Then the ChildObject received its own methods by chaining them onto its prototype:
ChildObject.prototype.methodName = function() {...};
Enter fullscreen mode Exit fullscreen mode
  • It's possible to override an inherited method. It's done the same way - by adding a method to ChildObject.prototype using the same method name as the one to override. Here's an example of Dog overriding the eat() method inherited from Animal:
function Animal() { }
Animal.prototype.eat = function() {
  return "nom nom nom";
};

function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.eat = function() {
  return "chew chew chew";
};
Enter fullscreen mode Exit fullscreen mode
  • If you have an instance let beagle = new Dog(); and you call beagle.eat(), this is how JavaScript looks for the method on beagle’s prototype chain:
  1. beagle => Is eat() defined here? No.

  2. Dog => Is eat() defined here? => Yes. Execute it and stop searching.

  3. Animal => eat() is also defined, but JavaScript stopped searching before reaching this level.

  4. Object => JavaScript stopped searching before reaching this level.

Top comments (0)