๐super
JS โฉ value โฉ object โฉ class โฉ inheritance โฉ super
access properties on object literal / class's prototype object. (
super.prop
/super[expr]
are valid in any method definition in object literal / class)invoke superclass constructor. (
super(...args)
is valid in class constructors)
// in any method definition
super.prop // parent's property
super[expr] // (same)
// in subclass constructor
super(...args) // superclass constructor
super
is not a variable that points to the prototype objectโ
attempting to read super itself is a
SyntaxError
โ
arrow functions do not have
super
. (๐ see: Arrow functions revisited)If accessed, itโs taken from the outer function.
๐ see: JavaScript.info
๐พ ็จๅผ๏ผ replit
// superclass
class A {
constructor(name) {
this.speed = 0;
this.name = name;
}
// โญ super.stop()
stop() {
this.speed = 0;
log(`${this.name} stands still.`);
}
}
class B extends A {
// โ
OK
stop() {
// ---------------------------------------------------
// โข arrow function doesn't have its own `super`.
// โข if accessed, itโs taken from the outer function.
// ---------------------------------------------------
// โญ call `super.stop()` after 1 sec
// โญโโ arrow func โโโฎ
setTimeout(() => super.stop(), 1000);
}
// โ doesn't work
stop2() {
// โญโโโโ โ regular func โโโโฎ
setTimeout( function(){ super.stop() }, 1000);
// ^^^^^
// โ SyntaxError: 'super' keyword unexpected here.
}
}
new B("Bunny").stop(); // "Bunny stands still." (after 1 sec)
Last updated
Was this helpful?