Dow*_*oat 10 javascript inheritance class super ecmascript-6
所以当我看到令人惊讶的事情时,我正在搞乱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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我创造了我的狗:
var mydog = new Dog("mydog",3);
mydog.speak();
Run Code Online (Sandbox Code Playgroud)
现在这个打印
Woof! I'm undefined and am 3
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,为什么super.name
未定义?我期待它mydog
在这种情况下.
Pau*_*aul 11
this
在父构造函数中仍然引用了狗,因此this.name = name
,name
直接在Dog
对象上设置属性,而不是在父对象上.使用this.name
将工作:
super.speak("Woof! I'm " + this.name + " and am " + this.age);
Run Code Online (Sandbox Code Playgroud)