有没有办法使用JavaScript访问子类中的超类变量?

问题描述 投票:3回答:1

当我遇到子类中的超类方法时,我正在学习JavaScript oops和一些示例示例,这可能是超级关键字但是当我尝试访问或返回超类的变量时,它返回undefined或我试过的各种子类变量获得变量的方式

我也去了this 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()
  
javascript ecmascript-6 ecmascript-5
1个回答
3
投票

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

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

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

在JavaScript中的所有类实际上都是语法糖之后,如果你使用babel将它转换为ES2015,你实际上可以看到它的实际效果。

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();
© www.soinside.com 2019 - 2024. All rights reserved.