๐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 constructorsuper
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)โญ๏ธ derived class initialization ็้็จ๏ผ
ๅ ๅท่ก super()ใ่ฅ parent class ็บ๏ผ
base class๏ผ
ๆฐๅข this ็ฉไปถ๏ผไธฆๅๅงๅ base class fieldsใ
ๅท่ก base constructorใ
derived class๏ผ (recursive) ้็จ 1. 2. 3. ๅ่ทไธ้ใ
ๅๅงๅ derived class fieldsใ
ๅท่ก derived constructor ่ฃก้ข super() ไปฅไธ็ๅๅงๅๅไฝใ
๐ see๏ผ override class fields
if a method does not use
super, then we can still consider it "free" (like a free function).itโs not safe to copy a method with super from one object to another. (a method remembers its [[HomeObject]])
๐ See๏ผ [[HomeObject]]
super ===
[[HomeObject]].[[Prototype]]โญ๏ธmust call super in override constructor.
override methods can call super.
derived class fields are initialized immediately after super().
a method's HomeObject is only used when calling super.
arrow function doesnโt have own this or super.
question class A vs. class A extends Object relates to super.
super is used in mixin inheritance.
TypedMap - subclass of Map that checks key/value types.
Last updated
Was this helpful?