在扩展类中运行构造函数

Run the constructor function in extended class

本文关键字:运行 构造函数 扩展      更新时间:2023-09-26

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

我尝试在Worker中添加constructor函数,如下所示:

"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

为什么会出现这种情况?此外,我该如何正确地执行此操作?

我想在w实例中访问type字段:

console.log(w.type);

您需要在扩展构造函数中调用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