Java Script Classes (method inheritance)

Hi Guys,
I have a question related to classes. I created a class “ShapeClass”, then I created a subclass “NewShape”. This what makes me wonder is, why the subclass “NewShape” didn’t inherit the function “calcPerimeter()” from “ShapeClass”. When I want to invoke this method with an instance of the “NewShape”, it returns NaN. How should I write this code, so that the subclass inherits also the method? Thanks in advance for help!

let shape5 = new NewShape(8)
shape5.calcPerimeter()
//returns NaN

class ShapeClass {
  constructor(name, sides, sideLength) {
    this.name = name;
  this.sides = sides;
  this.sideLength = sideLength;
  }
  calcPerimeter() {
    console.log(this.sides * this.sideLength)
  }
}

let shape3 = new ShapeClass('Square', 10, 5)
let shape4 = new ShapeClass('Triangle', 3, 3)


class NewShape extends ShapeClass {
  constructor(name, sides, sideLength) {
    super(sideLength);
    this.name = 'square'
    this.sides = 4
  }
  calcArea() {
    console.log(this.sides * this.sides)
  }
}

let shape5 = new NewShape(8)

Hi, maybe try to define your calcPerimeter() method on a global scope outside of your classes, so that any new classes can get access to it.

1 Like

Hi Kamil,
your child class does inherit the method from the parent class, but this.sideLength is undefined.
The constructors of both classes have three parameters each, but you’re passing just one argument to the instance shape5. Since the first parameter is name, the number 8 is taken for the name. If you change the order of the parameters in both classes and use sideLength as the first parameter, the argument will be given to that and your method will work.

2 Likes

Hi Chris, thank you - that would solve the issue itself, however it would be a nice, but still a way around the problem. The point in this exercise is, to make a subclass inherit from the parent class so that I can access a method from the parent class from the subclass and use it. The explanation why I cannot use the method from ShapeClass in NewShape that comes to my mind is, that I define this.name and this.sides in NewShape and, as I am using “this”, they apply only to the NewShape and are not taken by calcPerimeter() as this method sits in ShapeClass. If so, the question still remains - how should I write this code so that shape5.calcPerimeter() works.

Mirja - Thank You very much!:smiley:
Now it’s clear and obvious:D.
Cheers!

1 Like