I'm trying to access static method baseArea
from parent class cars
but it shows following error:
test.php:34 Uncaught TypeError: (intermediate value).baseArea is not a function
at Bike.get bikeArea [as bikeArea] (test.php:34)
at test.php:42
But it works fine when I use baseArea () {}
instead of static baseArea() {}
What am I doing wrong?
class Cars {
constructor(x, y) {
this.height = x;
this.width = y;
}
static baseArea() {
return 44;
}
}
class Bike extends Cars {
constructor(flag) {
super(flag, flag);
}
get bikeArea() {
return super.baseArea();
}
}
let bike = new Bike(10);
console.log(bike.bikeArea);
The static method are not called on the instance of class they are made to call directly on the class. So we can say that JavaScript provides us a static method that belongs to the class but not with the instance of the class. So like java we do not require an instance of the class to call the static method in JavaScript also.
The static method are not called on the instance of class they are made to call directly on the class. So we can say that JavaScript provides us a static method that belongs to the class but not with the instance of the class.
more flexible answer with classic js. You define "_parent = A.prototype;" in the child class, then you can call parent's methods with apply:
static The static keyword defines a static method or property for a class. Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.
It does not work because super.
is referencing a class instance. And a static method are not attached to instances but to class themselves.
However, the following will work:
class Cars {
constructor(x, y) {
this.height = x;
this.width = y;
}
static baseArea() {
return 44;
}
}
class Bike extends Cars {
constructor(flag) {
super(flag, flag);
}
get bikeArea() {
return Bike.baseArea();
}
}
Note the Bike.baseArea()
(which for the sake of readability can be called that way : Cars.baseArea()
).
In the example that you linked here, it is likely that it works because the pingpong method is also static AND called with Computer.pingpong() and not new Computer().pingpong() The whole chain is static. Maybe in that circumstances it succeed to resolve the super.
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