You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord开发中以消息作者用户名命名构造函数实例变量

解决动态变量名存储Discord用户实例的问题

嘿,我懂你的需求——想用消息作者的用户名作为变量名来存储person类的实例对吧?直接写var (msg.author.username) = ...肯定不行,因为JavaScript不允许把动态生成的字符串直接当作标识符(变量名)来用。不过有个简单又安全的办法,用对象作为容器来存储这些实例就完美解决了!

具体做法

  1. 先创建一个空对象,专门用来存放所有用户的person实例:
// 全局或者合适的作用域里定义这个容器
const userProfiles = {};
  1. 然后用方括号语法,把用户名作为对象的键来赋值:
// 替换你原来的错误赋值代码
userProfiles[msg.author.username] = new person(
  msg.author.username,
  1,
  msg.member.highestRole.name
);
  1. 之后要访问某个用户的实例时,同样用方括号语法(或者如果用户名是合法标识符,也可以用点语法):
// 获取当前消息作者的实例
const currentUser = userProfiles[msg.author.username];
// 访问实例属性
console.log(`${currentUser.name}的违规次数:${currentUser.violations}`);

为什么不直接用动态变量名?

你可能会想能不能用eval来实现,但真心不推荐——eval会执行任意字符串代码,不仅有安全风险(比如用户恶意构造用户名),而且代码可读性和维护性极差。用对象存储是行业内处理这类动态键值对的标准做法,既安全又清晰。

完整代码示例

function person(name, violations, role) {
  this.name = name;
  this.violations = violations;
  this.highestRole = role;
}

// 实例存储容器
const userProfiles = {};

// 存储当前消息作者的实例
userProfiles[msg.author.username] = new person(
  msg.author.username,
  1,
  msg.member.highestRole.name
);

// 测试访问
const testUser = userProfiles[msg.author.username];
console.log(testUser.highestRole); // 输出该用户的最高角色名

内容的提问来源于stack exchange,提问作者Logan Cook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:57:47