- 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);
- Then the
ChildObject
received its own methods by chaining them onto itsprototype
:
ChildObject.prototype.methodName = function() {...};
- 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";
};
- If you have an instance
let beagle = new Dog();
and you callbeagle.eat()
, this is how JavaScript looks for the method onbeagle’s
prototype
chain:
beagle
=> Iseat()
defined here? No.Dog
=> Iseat()
defined here? => Yes. Execute it and stop searching.Animal
=>eat()
is also defined, but JavaScript stopped searching before reaching this level.Object => JavaScript stopped searching before reaching this level.
Top comments (0)