Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ES6 super properties

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.

like image 921
Downgoat Avatar asked Dec 29 '15 18:12

Downgoat


People also ask

What is super in ES6?

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.

What is super () in constructor?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.

What is Subclassing in Javascript?

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 .

What is super () in angular?

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.


1 Answers

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);
like image 119
Paul Avatar answered Nov 29 '22 10:11

Paul