【问题标题】:Problem with importing JS Class in nodejs在 nodejs 中导入 JS 类的问题
【发布时间】:2020-03-26 21:40:53
【问题描述】:
class driverClass {
    static #MAX_INSTANCES = 2;
    static #instances = 0;

    #_id = 0;

    static existsID (id) {
        return driverClass.#_takenIDs.includes(id);
    }

    constructor (id) {
        driverClass.#instances++;

        this.#_id = id;

        driverClass.#_takenIDs.push(id);
    }
}
module.exports = driverClass;

在nodejs中

让 driverClass = require('./driverClass');

运行后出现此错误:

driverClass.js:2 静态 #MAX_INSTANCES = 2;

               ^

【问题讨论】:

标签: javascript node.js import


【解决方案1】:

您可能需要升级节点。私有静态字段为supported as of 12.0.0

如果我们先修改代码定义#_takenIDs...

$ cat driverClass.js
class driverClass {
    static #MAX_INSTANCES = 2;
    static #instances = 0;

    #_id = 0;
    #_takenIDs = [];

    static existsID (id) {
        return driverClass.#_takenIDs.includes(id);
    }

    constructor (id) {
        driverClass.#instances++;

        this.#_id = id;

        driverClass.#_takenIDs.push(id);
    }
}
module.exports = driverClass;

...并使用节点 v13.12.0 运行它,我们看到了正确的行为:

$ node --version
v13.12.0
$ node
Welcome to Node.js v13.12.0.
Type ".help" for more information.
> let driverClass = require('./driverClass');
undefined

但是,如果我们加载旧版本的节点,那么这将失败:

$ nvm use 10.14.1
Now using node v10.14.1 (npm v6.4.1)
$ node
> let driverClass = require('./driverClass');
./driverClass.js:2
    static #MAX_INSTANCES = 2;
           ^

SyntaxError: Invalid or unexpected token

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 2015-05-30
    • 2010-11-20
    • 2011-11-21
    • 2021-08-25
    • 1970-01-01
    • 2019-09-08
    • 2020-07-29
    相关资源
    最近更新 更多