node.js - 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
});
}
}
解决方案
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
});
}
}
推荐阅读
- r - An error while trying to get AOV results of repeated measures ANOVA
- subnet - 谷歌云数据融合子网问题
- oauth - 如何使 Google OAuth 应用程序的后端服务器接收“删除访问”事件或其他事件,例如“帐户禁用”、“令牌撤销”
- python - 如何修复:TypeError: relplot() 在使用 seaborn 绘制线图时获得了参数“x”的多个值
- asp.net-core - EF Core 一对一 - 仅针对一条记录返回结果
- turing-machines - 如何从 alpabet 创建机器
- python - 在拟合 multibomialNB 模型时,“int”和“str”实例之间不支持“<”
- excel - 加权平均反向
- javascript - 将 fetch api 调用存储为局部变量的函数(不是承诺)
- c++ - 与多个 for 循环相关的性能与从 multimap 获取数据的单个 for 循环相关的性能