ES6类:在超级方法中获取子类的正确名称

ES6 Classes: Get the proper name of a subclass in a super method

本文关键字:子类 获取 方法 ES6      更新时间:2024-04-14

假设我有以下内容:

class ThingWithWheels {
    constructor( numWheels ) {
        this.numWheels = numWheels
    }
    toString() {
        return this.constructor.name;
    }
}
class Car extends ThingWithWheels {
    constructor( color ) {
        super(4);
        this.color = color;
    }
    toString() {
        return `${this.color} ${super.toString()}`;
    }
}

这是非常标准的面向对象编程。然而,在NodeJS v5.6.0中,如果我制造了一辆红色汽车,并调用toString(),它将给出Red ThingWithWheels,而不是Red Car。当我调用super方法时,它将this视为ThingWithWheels,而不是Car

  1. 为什么会这样
  2. 有没有一种方法可以让超级方法正确命名

我刚刚在node.js 5.10.1中尝试过,它给了我"红色汽车",所以它可能是5.6中的一个错误。