调用javascript中已被子类覆盖的父类函数
我正在寻找一种方法来改变方法“answer(x,y)”在子类中的行为方式,并交换变量x和y,以便最后一条语句返回“true”。但是,任务是我不能更改子类,只能更改父类调用javascript中已被子类覆盖的父类函数,javascript,class,ecmascript-6,es6-class,Javascript,Class,Ecmascript 6,Es6 Class,我正在寻找一种方法来改变方法“answer(x,y)”在子类中的行为方式,并交换变量x和y,以便最后一条语句返回“true”。但是,任务是我不能更改子类,只能更改父类 您可以使用getter/setter在get上交换x和y 我所了解的是,在父函数中有一个交换函数,在子函数的应答函数中执行某些操作之前,需要调用它。 如果是这样,希望我已经回答了你下面的问题 class Parent { // some code swap (x, y) { le
您可以使用getter/setter在get上交换
x
和y
我所了解的是,在父函数中有一个交换函数,在子函数的应答函数中执行某些操作之前,需要调用它。 如果是这样,希望我已经回答了你下面的问题
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
可能是@diceler的复制品,反过来说。请仔细阅读这个问题。谢谢,它也很有效,但是我无法向子类添加方法
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