首页 > 解决方案 > JavaScript 父类和子类可以有同名的方法吗?

问题描述

以下作品。

class Parent {
    constructor(x) {
        this.x = x;
    }
    
    present() {
        return `I have a ${this.x}`;
    }
}


class Child extends Parent {
    constructor(x, y) {
        super(x);
        this.y = y;
    }

    // different name !!!
    show() {
        return `${this.present()}, it is a ${this.y}`;
    }
}


child = new Child("Tinggu", "Winggu");
console.log(child.present());

但是,与 Java 不同的是,Parent 和 Child 类中的同名方法似乎不起作用。

...

class Child extends Parent {
    constructor(x, y) {
        super(x);
        this.y = y;
    }

    // same name !!!
    present() {
        return `${this.present()}, it is a ${this.y}`;
    }
}

...

有没有办法使这项工作?

标签: javascriptinheritanceecmascript-6

解决方案


要调用具有相同名称的父方法,请使用super

    present() {
        return `${super.present()}, it is a ${this.y}`;
    }

推荐阅读