javascript - 运行扩展类中的构造函数

标签 javascript node.js class

我正在 Node.js 中使用 extends。我创建了一个名为 Person 的类,以及另一个扩展了 Person 类的类,名为 WorkerWorker 类有一个完美运行的 work 函数(它显示了 getName() 结果,在 Person 中定义)。我想为 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

关于javascript - 运行扩展类中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954107/

相关文章:

python - 在 Python 中访问外部函数和类

类对象字典的vba深层复制/克隆问题

javascript - for循环只循环一次

javascript - $('option[title= look]' 中的 Jquery 变量.show();

javascript - 如何将 Canvas 内容作为文件放入输入类型文件中

node.js - Meteor:如何将本地环境与生产环境分开?

javascript - 在使整个 div 可点击时,标签从开始的地方开始自动关闭

node.js - 解析字符串(node js)。将数字数组查找到字符串中

node.js - 可以删除从可读流中读取的数据吗?

java - 知道它来自哪个类(class)