我正在寻找一种改变方法的方法"回答(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
答案 0 :(得分:0)
您可以使用getter / setter在get上交换x
和y
。
答案 1 :(得分:0)
我明白你在父母中有一个交换功能,想在孩子的回答功能中做一些操作之前调用它。 如果是这样,希望我在下面回答了你的问题。
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