It seems you cannot call a superclass arrow function using super.methodName()
within a subclass:
class Parent {
constructor() {
console.log('in `Parent` constructor')
}
parentArrow = () => {
console.log('parentArrowFn')
}
parentMethod() {
console.log('parentMethod')
}
}
class Child extends Parent {
constructor() {
super()
console.log('in `Child` constructor')
}
childMethod() {
console.log('childMethod')
super.parentMethod() // works
super.parentArrow() // Error
}
}
(new Child()).childMethod();
Generates the error:
Uncaught TypeError: (intermediate value).parentArrow is not a function
at Child.childMethod (<anonymous>:21:15)
at <anonymous>:1:7
super
in subclasses?Public fields or "class instance fields" in es6 classes are not yet supported natively in all environments and even if it is you need to call it through a this
reference instead of super
as it becomes an instance property rather than a property on the prototype:
class Parent {
constructor() {
console.log('in `Parent` constructor')
}
parentArrow = () => {
console.log('parentArrowFn')
}
parentMethod() {
console.log('parentMethod')
}
}
class Child extends Parent {
constructor() {
super()
console.log('in `Child` constructor')
}
childMethod() {
console.log('childMethod')
super.parentMethod() // works
this.parentArrow() // Calls parentArrow
}
}
new Child().childMethod();
The need to call the arrow function using this
instead of super
is because when using an arrow function as a method the parentArrow
is added as a property of the instance rather than of the prototype and super
is used for calling methods declared on the prototype.
Your code can be translated to the code below, when you declare an arrow function inside a class:
constructor() {
console.log('in `Parent` constructor');
// becomes an instance property
this.parentArrow = () => { <----
console.log('parentArrowFn') |
} |
} |
parentArrow = () => { ----
console.log('parentArrowFn')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With