Technologies:
Tolerim
a day ago
An error of "Uncaught TypeError: Super expression must either be null or a function" is occurring when attempting to extend the static class.
static
in extended classes.
Main1
and Main2
, both of which are extended from the Base
class.
val
. It is crucial that Main1.val
and Main2.val
hold different values independently.
class Base {
static val;
static initialize(x) {
this.val = x;
}
}
class Main1 extends Base {
static showVal() {
return this.val;
}
}
class Main2 extends Base {
static showVal() {
return this.val * 2
}
}
var main1 = new Main1();
var main2 = new Main2();
main1.initialize(1);
main2.initialize(2);
console.log(main1.showVal());// should show 1
console.log(main2.showVal());// should show 4
Uncaught TypeError: Super expression must either be null or a function
Answers(1)
Tolerim
a day ago
Verified Answer
The error is occurring because the Base class does not have a constructor function defined. To solve this error, you can add a constructor function to the Base class and call it using the super keyword in the constructor functions of Main1 and Main2. Here's the updated code:
class Base{
static val;
static initialize(x){
this.val = x;
}
constructor(){
// add an empty constructor
}
}
class Main1 extends Base{
static showVal(){
return this.val;
}
constructor(){
super(); // call the constructor of the Base class
}
}
class Main2 extends Base{
static showVal(){
return this.val * 2
}
constructor(){
super(); // call the constructor of the Base class
}
}
var main1 = new Main1();
var main2 = new Main2();
main1.initialize(1);
main2.initialize(2);
console.log(main1.showVal()); // should show 1
console.log(main2.showVal()); // should show 4
In this updated code, we have added an empty constructor to the Base class, which allows us to use the super keyword in the constructor functions of Main1 and Main2. The super() call in each constructor function will call the constructor function of the Base class. This allows us to initialize the val variable in the Base class using the initialize function.
With these changes, the code should run without any errors and produce the expected results.