Is there a way to access superclass variables in subclass with JavaScript?

Jac*_*san 8 javascript ecmascript-5 ecmascript-6

I was learning JavaScript oops with some sample example when I came across to access superclass methods in subclass which is possible with super keyword but when I try to access or return a variable of super class it returns undefined or the sub class variable I tried in various way to get variable

I have also gone this Stack Overflow post.

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()
Run Code Online (Sandbox Code Playgroud)
  
Run Code Online (Sandbox Code Playgroud)

Ful*_*Guy 8

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

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

因此,我修改了您的示例代码并展示了如何通过调用super.fieldName. 在示例中,我ageDad类的原型中添加了一个属性并将其值设置为50,现在Sonprintvariable()中将super.age通过引用Dad类的原型来正确调用。

如果您使用 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();
Run Code Online (Sandbox Code Playgroud)