0

I'm looking for a way to change the way method "answer(x,y)" behaves in the Child class and swap the variables x and y so that the last statement would return "true". However, the task is that I can't change the Child class, only the 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
blz
  • 3
  • 3
  • Possible duplicate of [How do I override inherited methods when using JavaScript ES6/ES2015 subclassing](https://stackoverflow.com/questions/39886830/how-do-i-override-inherited-methods-when-using-javascript-es6-es2015-subclassing) –  Apr 29 '18 at 11:29
  • @diceler thats the other way round. Please read the question more carefully. – Jonas Wilms Apr 29 '18 at 11:40

2 Answers2

0

You could use getters / setters to swap x and y on get.

Show Spoiler

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

What i understood is you have a swap function in parent and want to call it before doing some operation inside answer function of child. If so, hopefully i have answered your query below.

   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
Karthik S
  • 313
  • 2
  • 7
  • Thanks, it works too, but the case was that I couldn't add methods to the Child class – blz Apr 29 '18 at 17:21