Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ES6类:在超级方法中获取子类的正确名称_Javascript_Node.js_Class_Ecmascript 6_Subclass - Fatal编程技术网

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

Javascript ES6类:在超级方法中获取子类的正确名称,javascript,node.js,class,ecmascript-6,subclass,Javascript,Node.js,Class,Ecmascript 6,Subclass,假设我有以下几点: class ThingWithWheels { constructor( numWheels ) { this.numWheels = numWheels } toString() { return this.constructor.name; } } class Car extends ThingWithWheels { constructor( color ) { super(4);

假设我有以下几点:

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()
,它将给出
带轮子的红色东西,而不是
红色汽车
。当我调用super方法时,它将
this
视为带轮子的
thing
而不是
Car

  • 为什么会这样
  • 有没有一种方法可以让超级方法的名称正确

  • 我刚刚在node.js 5.10.1中尝试了这个,它给了我“红色汽车”,所以它可能是5.6中的一个bug。

    这里哪些是从其他继承的?你没有显示任何继承。你的意思是类Car扩展ThingWithWheels,阅读这里,你必须做更多的研究:我忘了键入“extends ThingWithWheels”。不会改变行为。结果是,当您意外地创建了一个超类而不是子类的实例时,您得到了错误的名称。羞耻感加剧