Javascript 在扩展类中运行构造函数

Javascript 在扩展类中运行构造函数,javascript,node.js,class,Javascript,Node.js,Class,我正在Node.js中玩扩展。我创建了一个名为Person的类和另一个扩展Person的类,名为Worker。Worker类有一个工作正常的work函数(它显示getName()结果,在Person中定义)。我想为Worker构造函数添加另一个参数 我尝试通过在工作者中添加构造函数函数,如下所示: "use strict"; class Person { constructor (name) { this.name = name; } getName (

我正在Node.js中玩
扩展。我创建了一个名为
Person
的类和另一个扩展
Person
的类,名为
Worker
Worker
类有一个工作正常的
work
函数(它显示
getName()
结果,在
Person
中定义)。我想为
Worker
构造函数添加另一个参数

我尝试通过在
工作者
中添加
构造函数
函数,如下所示:

"use strict";

class Person {
    constructor (name) {
        this.name = name;
    }
    getName () {
        return this.name;
    }
}

class Worker extends Person {
    // Without this constructor, everything works correctly
    // But I want to add the type field
    constructor (name, type) {
        console.log(1);
        // this.type = type;
    }
    work () {
        console.log(this.getName() + " is working.");
    }
}

var w = new Worker("Johnny", "builder");
w.work();
运行此命令时,我会出现以下错误:

path/to/my/index.js:14
        console.log(1);
                ^

ReferenceError: this is not defined
    at Worker (/path/to/my/index.js:14:17)
    at Object.<anonymous> (/path/to/my/index.js:22:9)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

您需要在扩展构造函数中调用
super()
。否则,它不会在
Person
类中调用构造函数

class Person {
    constructor (name) {
        this.name = name;
    }
    getName () {
        return this.name;
    }
}

class Worker extends Person {
    constructor (name, type) {
        super(name);
        this.type = type;
    }
    work () {
        console.log(this.getName() + " is working.");
    }
}
以下各项现在应该可以发挥作用:

var w = new Worker("Johnny", "builder");
w.work();
console.log(w.type); //builder
var w = new Worker("Johnny", "builder");
w.work();
console.log(w.type); //builder