ES6 类: 在超方法中获取子类的专有名称
ES6 Classes: Get the proper name of a subclass in a super method
假设我有以下内容:
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
。
- 这是为什么?
- 有没有办法在 super 方法正确命名的情况下执行此操作?
我刚刚在 node.js 5.10.1 中尝试过,它给了我 "Red Car",所以它可能是 5.6 中的一个错误。
假设我有以下内容:
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
。
- 这是为什么?
- 有没有办法在 super 方法正确命名的情况下执行此操作?
我刚刚在 node.js 5.10.1 中尝试过,它给了我 "Red Car",所以它可能是 5.6 中的一个错误。