What's the purpose of this example?

Hey I’m at the Object Oriented course section and there is an example stating:

If you have an instance let duck = new Bird(); and you call duck.eat() , this is how JavaScript looks for the method on duck’s prototype chain:

  1. duck => Is eat() defined here? No.
  2. Bird => 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.

I understand the rest of the problem and got the solution, but just wanted to make sure I understand this. Please expand on this if possible.

Exercise: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#object-oriented-programming

Can you provide the link to the challenge rather than the category of the challenge? I tried to point to a challenge that I thought was the right one but wasn’t sure and reverted it (this is why your post has 2 edits, sorry bout that ;D)

2 Likes

Yeah sorry I must’ve grabbed the wrong link :pray:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods

Its about inheritance isnt it?
Object → Animal → Bird → Duck

Javascript searches from Duck going backwards to find which object is duck inheriting eat from. If eat is a property that was defined in Bird, Javasript stops searching otherwise it continues to Animal and to Object until it finds the object were eat is defined.

1 Like

Right I just wasn’t sure how it fit in. It was a warning not to do that because perhaps it’s a common mistake?

You might be talking about the common argument that “inheritance is bad”. This is mainly due to the fact the more you build on other code, it makes it harder to refactor later.

So for example, if you had an Animal class that had a method getLegs(), and you inherit it with a new class of Snake, suddenly getLegs() makes no sense. Thus requiring a refactor of the Animal class, which could affect all your other classes that were inheriting Animal!

This could be a major pain, and is usually why large amounts of inheritance can get really tricky really fast. At the same time if what your modeling makes sense and doesn’t change much (IE don’t assume all animals have legs!) it can still work well to model real world stuff :slight_smile: