简体   繁体   中英

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);

You can chnage your

get bikeArea(){
   return super.baseArea();
}

to

get bikeArea(){
   return Cars.baseArea();
}

Or you can simply use that:

class Cars {
    constructor(x, y) {
        this.height = x;
        this.width = y;
    }

    baseArea() {
        return 44;
    }
}

class Bike extends Cars {
    constructor(flag) {
        super(flag, flag);
    }

    bikeArea() {
        return super.baseArea();
    }
}

let bike = new Bike(10);
console.log(bike.bikeArea());

It does not work because super. is referencing a class instance. And a static method is 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.

You can simply call Bike.baseArea() instead of bike.bikeArea() as it has been extended to include Cars .

or

You could change,

get bikeArea() {
    return super.baseArea();
}

to,

static bikeArea() {
    return super.baseArea();
}

Thereby allowing you to call it as Bike.bikeArea() .

To call parent's static method on child's non-static method using super keyword

class Bike extends Cars {
    get bikeArea() {
        return super.constructor.baseArea();
    }
}

However, to call parent's static method on child's static method using super keyword

class Bike extends Cars {
    static bikeArea() {
        return super.baseArea();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM