๐super
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
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 โ
arrow functions do not have super
. (๐ see: )
If accessed, itโs taken from the outer function
๐พ ็จๅผ๏ผ
๐ see: JavaScript.info
ๆฐๅข this ็ฉไปถ๏ผไธฆๅๅงๅ base class fieldsใ
ๅท่ก base constructorใ
derived class๏ผ (recursive) ้็จ 1. 2. 3. ๅ่ทไธ้ใ
ๅๅงๅ derived class fieldsใ
ๅท่ก derived constructor ่ฃก้ข super() ไปฅไธ็ๅๅงๅๅไฝใ
๐ See๏ผ [[HomeObject]]
// 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)