TIL super keyword in Javascript classes
POSTED ON:
TAGS: javascript classes mdn codepen
The super
keyword in JavaScript acts as a reference variable to the parent class.
It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.job = 'Barbarian'
}
atWork() {
return this.name + " is exploring";
}
atHome() {
return this.name + " will relax"
}
}
class Character extends Person {
constructor(name, age, job) {
super(name, age, job);
}
profession() {
return this.name +
` is a ${this.age}yo ${this.job}`;
}
doTasks() {
// If you're using parent methods, you can use this or super to call them
return `${this.profession()}, and ${super.atWork()}. Then ${this.atHome()}.` ;
}
}
const hero = new Character("Conan", 30);
console.log(hero.profession());
console.log(hero.atHome());
console.log(hero.doTasks());
See the Pen by rockykev (@rockykev) on CodePen.
Via MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super
Related TILs
Tagged: javascript