0

I am new to JS, I am particularly confused by following code:

class One{
    constructor(num){
        this.num = num;
    }

    add(){
        this.num += 1;
    }

    showInfo(){
        this.add();
        console.log(`The result is ${this.num}`);
    }
}

class Ten extends One{
    constructor(num){
        super(num);
    }

    add(){
        this.num += 10;
    }
}

let t = new Ten(1);
t.showInfo();
// The result is 11

I thought the result should be 2, because showInfo is executed in One so add should be executed in One as well, furthermore, showInfo is only defined in One, but why is One.showInfo calling Ten.add instead of One.add?

I will be so glad if someone offer some explanation.

3
  • 3
    Are you aware of how polymorphism works? Commented Nov 20, 2020 at 6:54
  • Try console.log(this) in your showInfo - you'd not be surprised anymore. Commented Nov 20, 2020 at 6:59
  • For any Ten instance Ten's prototypal add method shadows the one implemented by One. If one wants to support the latter for any Ten instance one needs to implement another (prototypal) method which does a super delegation ... e.g. addOne() { return super.add(); }. Then one can do e.g. const t = new Ten(1); t.add() /* 11 */; t.addOne() /* 12 */; Commented Nov 20, 2020 at 13:02

2 Answers 2

1

The showInfo () is inherited by the Ten class and it is executed on the Ten class calling the add () of the Ten class; Yielding 11;

To return 2 add () implementation in Ten Class should call super.add() instead

Sign up to request clarification or add additional context in comments.

Comments

0
add(){
        return super.add();
    }

Go through the below :)

https://javascript.info/class-inheritance

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.