访问 ES6 超级属性
Accessing ES6 super properties
所以当我看到一些令人惊讶的东西时,我正在乱搞 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
在parent构造函数中仍然引用狗,所以this.name = name
,直接在[=14=上设置属性name
] object 而不是 parent。使用 this.name
将起作用:
super.speak("Woof! I'm " + this.name + " and am " + this.age);
所以当我看到一些令人惊讶的东西时,我正在乱搞 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
在parent构造函数中仍然引用狗,所以this.name = name
,直接在[=14=上设置属性name
] object 而不是 parent。使用 this.name
将起作用:
super.speak("Woof! I'm " + this.name + " and am " + this.age);