有没有一种方法可以使用JavaScript访问子类中的超类变量?

12
我在学习JavaScript面向对象编程时,使用一些示例代码,发现可以使用super关键字访问子类中的超类方法,但是当我试图访问或返回超类的变量时,它会返回undefined或者子类变量。我尝试了多种方法来获取变量。

我还查看了这篇Stack Overflow帖子。

class dad {
    constructor(name) {
        this.name = name;
    }
    printname() {
        console.log(this.name);
        var a = 2;
        return a;
    }
    sendVal() {
        console.log(this.name);
        var a = 2;
        return this.name;
    }
}

class son extends dad {
    constructor(name) {
        super(name);
    }
    printname() {
        console.log(super.printname());

    }
    printvariable() {
        console.log(super.name);

    }
    getvalue() {
        console.log(super.sendVal())
    }
}

var o1 = new dad('jackson');
var o2 = new son('jack')

o1.printname()
o2.printname()
o2.printvariable()
o2.getvalue()
  


1
你当然可以调用来自超类的方法,但是你期望 console.log(super.name)console.log(this.name) 有什么不同呢? - Nicholas Tower
1个回答

13

当你使用super.fieldName访问父类的字段时,实际上是在父类的prototype上查询字段名称。

因此你可能认为从Son构造函数调用super(name);会将name设置在父类原型中,但事实并非如此,它实际上设置了被Son类继承的name属性,在使用this.name时可以访问该属性。

所以我修改了你的示例代码,并展示了如何通过调用super.fieldName实际获取值。在示例中,我在Dad类的原型中添加了一个属性age,并将其值设置为50,现在在Son类中,printvariable()将正确通过引用Dad类的原型来调用super.age

如果您使用Babel将其转换为ES2015,则可以看到它实际上运行。毕竟,JavaScript中的类实际上是语法糖。

class Dad {
    constructor(name) {
        this.name = name;
        Dad.prototype.age = 50; //adding property to prototype
    }
    printname() {
        console.log(this.name);
        var a = 2;
        return a;
    }
    sendVal() {
        console.log(this.name);
        var a = 2;
        return this.name;
    }
}

class Son extends Dad {
    constructor(name) {
        super(name);
    }
    printname() {
        console.log(super.printname());

    }
    printvariable() {
        console.log(`super.name will be undefined, as not present in prototype of the Dad class: ${super.name}`);
        console.log(`super.age will have a value of 50, present in the prototype of the Dad class: ${super.age}`);
        console.log(`this.name will be jack, as it is set from the constructor of the Son class: ${this.name}`);

    }
    getvalue() {
        console.log(super.sendVal());
    }
}

var o1 = new Dad('jackson');
var o2 = new Son('jack')

o1.printname();
o2.printname();
o2.printvariable();
o2.getvalue();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接