Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call static method in JavaScript parent class

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);
like image 731
Vikas Avatar asked Aug 18 '17 12:08

Vikas


People also ask

How to call a static method in JavaScript without instance?

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.

Which static method does not belong to the class?

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.

How to call parent's methods from child class in JavaScript?

more flexible answer with classic js. You define "_parent = A.prototype;" in the child class, then you can call parent's methods with apply:

What is the use of Static Static in Java?

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.


1 Answers

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.

like image 180
Anthony Raymond Avatar answered Sep 28 '22 10:09

Anthony Raymond