Home > Software engineering >  Javascript Inheritance Explanation
Javascript Inheritance Explanation

Time:08-01

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.

CodePudding user response:

speedboat and boat are literally instances of the SpeedBoat and Boat classes respectively, which inheritance does not come into play.

You might be wondering why the Yatch class isn't inherited from the Boat class, hence why yatch isn't an instance of the Boat class. It's missing the extends keyword, which formally states that Yatch is inherited from the Boat class.

class Yatch extends Boat{
}

Will functionally do the same with the inheritance included.

CodePudding user response:

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

  • Related