Search code examples
javascriptinheritancelogicprototype

Javascript Inheritance Explanation


I am trying to understand the inheritance and prototype logic of the JS. So I have a question.

To demonstrate it I wrote that kind of code...

class Boat {
 constructor() {
 
 }
}

class SpeedBoat {
 constructor() {
   new Boat();
 }
}


class Yatch {
  constructor() {
     new Boat()
  }
}

const yatch = new Yatch()
const speedBoat = new SpeedBoat()
const boat = new Boat()

console.log(yatch instanceof Boat)
console.log(speedBoat instanceof SpeedBoat)
console.log(boat instanceof Boat)

'''

The console results are;

false true true

I will be appreciate to anyone who can explain this results in detail. Thank you.


Solution

  • Last two console logs give you true because

    • speedBoat instance is created from SpeedBoat class => speedBoat = new SpeedBoat()
    • Similarly, boat instance is created from Boat class => boat = new Boat()

    The fist one gives you false because

    yatch instance is created from Yatch class => yatch = new Yatch() and you're checking if this yatch instance is an instance of Boat class which is NOT TRUE

    Why inheritance is not working for you when you do - console.log(yatch instanceof Boat)

    • Inheritance is the concept where Child class (Yatch in this case) is getting all its properties and methods from the parent class Boat. But that's not happening in your case as you're not inheriting it properly.
    • In your Yatch classes' constructor (and all other constructors), you're defining like this:

    The below code doesn't work

    class Yatch {
      constructor() {
         new Boat() // this line is creating object/instance of Boat class and this object is not pointing to any variable and hence will be garbage collected (will be removed from the memory)
      }
    }
    

    How to define inheritance?

    You need to use extends keyword in the Child class (Yatch) and tell which should be the parent class (Boat) like this

    class Yatch extends Boat{
      super() { // this super keyword calls the constructor of parent (Boat class)
         new Boat()
      }
    }
    

    Modified working code - https://codepen.io/sandeep194920-the-flexboxer/pen/bGvaoyW?editors=1111