当我看到一些令人惊讶的东西时,我正在摆弄 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/