代码有一个拼写错误,Son 类的构造函数应该是 'constructor' 而不是 'construstor':

class Son extends Father {
    constructor(x, y) { // 正确写法
        super(x, y)
    }
}

错误原因:

在 JavaScript 中,子类必须使用 'constructor' 关键字来定义构造函数,该关键字用于初始化子类实例。拼写错误 'construstor' 会导致代码无法正确识别构造函数,从而引发错误。

解决方案:

将 'construstor' 更正为 'constructor',确保代码能够正确执行。

代码示例:

class Father {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    sum() {
        console.log(this.x + this.y)
    }
}

class Son extends Father {
    constructor(x, y) {
        super(x, y)
    }
}

var son = new Son(3, 5)
console.log(son.sum());

注意:

在 JavaScript 中,子类必须调用 super() 方法来调用父类的构造函数,以确保父类属性被正确初始化。

JavaScript 继承错误:Son 类构造函数拼写错误

原文地址: https://www.cveoy.top/t/topic/ohO0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录