Skip to content
Advertisement

How can I pass a value from Child class to Parent class in JavaScript

I create One Parent class and Two Child classes.Two Child classes each have a method to calculate the value of Area.

Whenever I call a7.areaPrint(). It shows me undefined. But I can get the result by c7.calculate() && s7.calculate() in console.

How can I pass those two area value to Parent class and Print it?

c7.calculate() && s7.calculate() will be printed on Parent class.

function myExtend(Parent, Child) {
    Child.prototype = Object.create(Parent.prototype)
    Parent.prototype.constructor = Parent
}

function Area(circleArea, squareArea) {
    this.areaPrint = function () {
        console.log("The Circle area is: " + Circle.call(this, circleArea))
        console.log("The Square area is: " + Square.call(this, squareArea))
    }
}
function Circle(r) {
    this.radius = r
    this.calculate = function () {
        var circleArea = (Math.PI * Math.sqrt(this.radius, 2)).toFixed(2)
        return circleArea;
    }
}

function Square(s) {
    this.side = s
    this.calculate = function () {
        var squareArea = (Math.sqrt(this.side, 2)).toFixed(2)
        return squareArea;
    }
}

//Create Prototype(Area > Circle)
myExtend(Area, Circle)

//Prototype Member
Circle.prototype.perimeter = function (D) {
    return (Math.PI * D).toFixed(2)
}

//Create Prototype(Area > Square)
myExtend(Area, Circle)


var c7 = new Circle(5)
var s7 = new Square(5)
var a7 = new Area()

console.log()

a7.areaPrint()

Advertisement

Answer

Not sure if I understand your question. Up to what I understand that needs fix, you need to pass the arguments in in the line var a7 = new Area() -> var a7 = new Area(c7, s7) and in the area calculate code from Circle.call(this, circleArea) to the function call circleArea.calculate().

function myExtend(Parent, Child) {
  Child.prototype = Object.create(Parent.prototype)
  Parent.prototype.constructor = Parent
}

function Area(circleArea, squareArea) {
  this.areaPrint = function() {
    console.log("The Circle area is: " + circleArea.calculate());
    console.log("The Square area is: " + squareArea.calculate());
  }
}

function Circle(r) {
  this.radius = r
  this.calculate = function() {
    var circleArea = (Math.PI * Math.sqrt(this.radius, 2)).toFixed(2)
    return circleArea;
  }
}

function Square(s) {
  this.side = s
  this.calculate = function() {
    var squareArea = (Math.sqrt(this.side, 2)).toFixed(2)
    return squareArea;
  }
}

//Create Prototype(Area > Circle)
myExtend(Area, Circle)

//Prototype Member
Circle.prototype.perimeter = function(D) {
  return (Math.PI * D).toFixed(2)
}

//Create Prototype(Area > Square)
myExtend(Area, Square)


var c7 = new Circle(5)
var s7 = new Square(5)
var a7 = new Area(c7, s7)

console.log()

a7.areaPrint();
Advertisement