TIL super()
POSTED ON:
What is super()?
When you extend classes, you'll see it a bunch. Especially in old-school Class-based React.
It looks like this:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
What does it mean?
When you use super(), it's like you're telling the new object to copy everything from the old object first, and then add or change anything else that's different.
Using super() #
// parent constructor
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name} barks!`);
}
}
const myDog = new Dog('Rufus', 'Golden Retriever');
myDog.speak(); // "Rufus makes a noise."
myDog.bark(); // "Rufus barks!"
If you don't use super() #
- In a child class constructor, this cannot be used until super is called.
- ES6 class constructors MUST call super if they are subclasses, or they must explicitly
return some object to take the place of the one that was not initialized.
Via: https://stackoverflow.com/a/31079103/4096078
If you didn't include super(), this happens.
Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
// parent constructor
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
// Uncommenting the line below will cause an error.
// this.name = name;
this.breed = breed;
}
bark() {
console.log(`${this.name} barks!`);
}
}
const myDog = new Dog('Rufus', 'Golden Retriever');
myDog.speak(); // This will cause an error because the `name` property is not defined.
myDog.bark(); // This will work because the `bark()` method is defined in the `Dog` class.
REF:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super
Related TILs
Tagged: mdn