javascript - 访问 ES6 super 属性

标签 javascript class inheritance ecmascript-6 super

当我看到一些令人惊讶的东西时,我正在摆弄 ES6 类:

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak(sound) {
        console.log(sound);
    }
}

class Dog extends Animal {
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    speak() {
        super.speak("Woof! I'm " + super.name + " and am " + this.age);
    }
}

然后,我创造了我的狗:

var mydog = new Dog("mydog",3);
mydog.speak();

现在打印

Woof! I'm undefined and am 3

所以我的问题是,为什么 super.name 未定义?在这种情况下,我希望它是 mydog

最佳答案

this在父构造函数中仍然引用狗,所以this.name = name , 设置属性 name直接在Dog对象而不是其父对象。使用 this.name将工作:

super.speak("Woof! I'm " + this.name + " and am " + this.age);

关于javascript - 访问 ES6 super 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34517071/

相关文章:

javascript - 如果未设置 cookie,如何为某些浏览器显示消息

javascript - 添加更多字符时正则表达式不匹配

javascript - 从 2 点求解指数方程

java - 在父类(super class)和子类中实现同名但不同实现的方法

java - 从ListQueue类调用 protected 方法 "Front",该方法实现了Queue接口(interface)

javascript - Jquery点击元素外部隐藏其他元素

c++ - 为什么枚举类优于普通枚举?

VBA 类 - 如何让一个类拥有额外的类

c++ - 错误 C2679 : binary '+' : no operator found which takes a right-hand operand of type

c# - 使用三元运算符了解 C# 编译错误