You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何将子类计算的面积值传递给父类并打印

问题代码核心错误点

  • 继承工具函数myExtend逻辑错误:原代码错误修改了父类构造函数指向,正确逻辑需要修正子类原型的constructor指向为子类自身
  • 继承绑定错误:给Square绑定继承时重复绑定了Circle,导致Square完全没有继承到Area的方法
  • 面积计算公式错误:圆和正方形的面积计算都误用了开平方方法Math.sqrt,应该用平方计算实现
  • Area的areaPrint方法逻辑错误:直接调用Circle.call/Square.call只会执行构造函数初始化属性,不会调用calculate方法返回面积,且创建a7实例时没有传入对应子类实例,无法获取计算结果
  • 继承使用逻辑偏差:你的继承方向是Circle、Square继承Area,也就是说子类实例本身就可以调用继承来的areaPrint方法打印自身面积,不需要单独创建Area实例跨实例读取结果

修正方案(两种常用实现)

方案1:子类实例调用继承来的areaPrint打印自身面积

// 修正继承工具函数
function myExtend(Parent, Child) {
    Child.prototype = Object.create(Parent.prototype)
    // 修正:把子类原型的constructor指回子类本身
    Child.prototype.constructor = Child
}

// 父类Area
function Area() {
    this.areaPrint = function () {
        // 直接调用当前实例的calculate方法,子类都实现了该方法
        console.log(`The area is: ${this.calculate()}`)
    }
}
// 圆子类
function Circle(r) {
    this.radius = r
    this.calculate = function () {
        // 修正圆面积公式:πr²
        var circleArea = (Math.PI * Math.pow(this.radius, 2)).toFixed(2)
        return circleArea;
    }
}
// 正方形子类
function Square(s) {
    this.side = s
    this.calculate = function () {
        // 修正正方形面积公式:边长平方
        var squareArea = (Math.pow(this.side, 2)).toFixed(2)
        return squareArea;
    }
}

// 绑定继承
myExtend(Area, Circle)
myExtend(Area, Square) // 修正:之前错误绑定了两次Circle

// Circle原型扩展方法
Circle.prototype.perimeter = function (D) {
    return (Math.PI * D).toFixed(2)
}

// 实例化调用
var c7 = new Circle(5)
var s7 = new Square(5)

c7.areaPrint() // 输出 The area is: 78.54
s7.areaPrint() // 输出 The area is: 25.00

方案2:Area实例同时打印两个子类实例的面积

如果你需要单独的a7实例同时打印圆和正方形的面积,可以调整父类逻辑如下:

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

// 父类接收两个子类实例作为参数
function Area(circleIns, squareIns) {
    this.areaPrint = function () {
        console.log("The Circle area is: " + circleIns.calculate())
        console.log("The Square area is: " + squareIns.calculate())
    }
}

function Circle(r) {
    this.radius = r
    this.calculate = function () {
        return (Math.PI * Math.pow(this.radius, 2)).toFixed(2)
    }
}
function Square(s) {
    this.side = s
    this.calculate = function () {
        return (Math.pow(this.side, 2)).toFixed(2)
    }
}

myExtend(Area, Circle)
myExtend(Area, Square)

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

var c7 = new Circle(5)
var s7 = new Square(5)
// 实例化Area时传入两个子类实例
var a7 = new Area(c7, s7)

a7.areaPrint()
// 输出:
// The Circle area is: 78.54
// The Square area is: 25.00

内容的提问来源于stack exchange,提问作者mrhrifat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:36:05