简体   繁体   English

javascript:类继承方法调用

[英]javascript: class inheritance method call

I am new to JS, I am particularly confused by following code:我是 JS 新手,我对以下代码特别困惑:

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 ?我认为结果应该是 2,因为showInfoOne执行,所以add应该在One执行,而且showInfo只在One定义,但为什么One.showInfo调用Ten.add而不是One.add

I will be so glad if someone offer some explanation.如果有人提供一些解释,我会很高兴。

The showInfo () is inherited by the Ten class and it is executed on the Ten class calling the add () of the Ten class; showInfo()由Ten类继承,在Ten类上调用Ten类的add()执行; Yielding 11;产量 11;

To return 2 add () implementation in Ten Class should call super.add() instead返回 2 add() 在十类中的实现应该调用 super.add() 代替

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

Go through the below :)通过以下:)

https://javascript.info/class-inheritance https://javascript.info/class-inheritance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM