How can we invoke the parent's method, when a child has a method with the same name in JavaScript? Anything like type casting in Java here? [duplicate]

流过昼夜 提交于 2020-08-10 01:23:07

问题


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;
    }

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


child = new Child("Tinggu", "Winggu");
console.log(child.present()); // invokes the child version

How would I invoke the parent's method, from the child object? Type-Casting like Java doesn't seem to help.


回答1:


The methods inside the class get added to Parent.prototype. So, you could call the Parent's present function with the child object as this

Parent.prototype.present.call(child)

Here's a snippet:

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;
    }

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

const child = new Child("Tinggu", "Winggu");
console.log(
  Parent.prototype.present.call(child)
);


来源:https://stackoverflow.com/questions/63167043/how-can-we-invoke-the-parents-method-when-a-child-has-a-method-with-the-same-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!