Today I Learned - Rocky Kev

TIL super keyword in Javascript classes

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.