So I was messing around with ES6 classes when I saw something surprising:
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);
}
}
Then, I created my dog:
var mydog = new Dog("mydog",3);
mydog.speak();
Now this prints
Woof! I'm undefined and am 3
So my question is, why is super.name
undefined? I'm expecting it to be mydog
in this case.
So I was messing around with ES6 classes when I saw something surprising:
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);
}
}
Then, I created my dog:
var mydog = new Dog("mydog",3);
mydog.speak();
Now this prints
Woof! I'm undefined and am 3
So my question is, why is super.name
undefined? I'm expecting it to be mydog
in this case.
1 Answer
Reset to default 18this
in the parent constructor still refers to the dog, so this.name = name
, sets the property name
directly on the Dog
object and not on its parent. Using this.name
will work:
super.speak("Woof! I'm " + this.name + " and am " + this.age);
super
can only be used to access properties on the prototype. Usingthis.name
you are assigning to the instance and so always need to access it usingthis
– CodingIntrigue Commented Dec 29, 2015 at 18:52