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.
The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor. The super. prop and super[expr] expressions are valid in any method definition in both classes and object literals.
The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.
Subclassing is a term that refers to inheriting properties for a new object from a base or superclass object. In traditional object-oriented programming, a class B is able to extend another class A . Here we consider A a superclass and B a subclass of A . As such, all instances of B inherit the methods from A .
super is ES6 syntax that cannot be used outside the method where it's used. Given there is Foo class that extends Bar , super keyword is interpreted as Bar in Foo constructor and static methods and as Bar.
this 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With