【问题标题】:Call a parent class function in javascript that been overwritten by child class在javascript中调用被子类覆盖的父类函数
【发布时间】:2018-04-29 11:25:31
【问题描述】:

我正在寻找一种方法来更改方法“answer(x,y)”在 Child 类中的行为方式并交换变量 x 和 y,以便最后一条语句返回“true”。但是,任务是我不能更改 Child 类,只能更改 Parent。

class Parent {
    // some code
}
class Child extends Parent {
    answer(x, y) {
        this.x = x;
        this.y = y;
        return 75 - this.x + this.y;
    }
}
let v = new Child();
v.answer(5, 15) === 65; //should be true
v.answer(15, 5) === 85; //should be true

【问题讨论】:

标签: javascript class ecmascript-6 es6-class


【解决方案1】:

您可以使用 getter / setter 在 get 上交换 xy

Show Spoiler

【讨论】:

    【解决方案2】:

    我的理解是您在父级中有一个交换函数,并且想在子级的应答函数中执行一些操作之前调用它。 如果是这样,希望我在下面回答了您的问题。

       class Parent {
            // some code
           swap (x, y) {
            let temp = this.x;
            this.x = this.y;
            this.y = temp;
           }
        }
        class Child extends Parent {
            answer(x, y) {
                super.swap.call(this, x, y); // Call parent func that swaps variable using child context
                this.x = x;
                this.y = y;
                return 75 - this.x + this.y;
            }
        }
        let v = new Child();
        v.answer(5, 15) === 65; //should be true
        v.answer(15, 5) === 85; //should be true
    

    【讨论】:

    • 谢谢,它也可以,但情况是我无法向 Child 类添加方法
    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2020-04-10
    相关资源
    最近更新 更多