首页 > 解决方案 > NodeJS 中未定义私有字段错误

问题描述

我正在尝试在 NodeJS 中使用私有类字段。我正在通过带有 babel-parser 和 Babel 的 ES-Lint 运行此代码。在 VS Code 中,我有 ES Lint 显示错误。下面列出了错误。它发生在 IORedis 构造函数的身份验证对象内部的赋值期间。当我在 Babel 中运行代码时,我也会遇到同样的错误。

解析错误:未定义私有名称#password

class MyRedis {
  constructor(password, host) {

    this.host = host || process.env.HOST;
    this.#password = password || process.env.PASSWORD;

    if (!this.#password) { throw new Error('Password not set'); }

    this.client = new IORedis({
      // removed some items for brevity
      host: this.host,
      password: this.#password // error is here
    });
  }
}

标签: node.jsclassbabeljseslintprivate

解决方案


this解决方案是在类的顶部声明私有实例变量。您必须包含 ,hash因为它是名称本身的一部分。在MDN 文档中查看更多信息。

class MyRedis {
  #password; // declaration creates the private variable this.#password

  constructor(password, host) {

    this.host = host || process.env.HOST;
    this.#password = password || process.env.PASSWORD;

    this.client = new IORedis({
      // removed some items for brevity
      host: this.host,
      password: this.#password
    });
  }
}

推荐阅读