繁体   English   中英

javascript:类继承方法调用

[英]javascript: class inheritance method call

我是 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

我认为结果应该是 2,因为showInfoOne执行,所以add应该在One执行,而且showInfo只在One定义,但为什么One.showInfo调用Ten.add而不是One.add

如果有人提供一些解释,我会很高兴。

showInfo()由Ten类继承,在Ten类上调用Ten类的add()执行; 产量 11;

返回 2 add() 在十类中的实现应该调用 super.add() 代替

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

通过以下:)

https://javascript.info/class-inheritance

暂无
暂无

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

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