【问题标题】:Is there a way to access superclass variables in subclass with JavaScript?有没有办法使用 JavaScript 访问子类中的超类变量?
【发布时间】:2023-03-29 22:25:01
【问题描述】:

当我遇到访问子类中的超类方法时,我正在通过一些示例示例学习 JavaScript oops,这可以使用 super 关键字 但是当我尝试访问或返回超类的变量时,它返回未定义或我尝试以各种方式获取变量的子类变量

我也发了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()
  

【问题讨论】:

  • 您当然可以调用来自超类的方法,但是您希望console.log(super.name)console.log(this.name) 做什么不同?

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2020-06-04
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多