所以我的意思是我想导出函数中的某个对象。
async function Set(x) {
module.exports["x"] = x
}
这似乎不起作用,并且变得不确定,你们能帮忙吗?
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
var args = message.content.split(/[ ]+/)
const Cargs = message.content.slice(prefix.length).trim().split(/[ ]+/);
const command = Cargs.shift().toUpperCase();
if (client.commands.get(command)) {
await Set(message)
client.commands.get(command).execute()
}
})
答案 0 :(得分:1)
表面上,您想要做的事情是完全可能的。
但是,您需要注意模块和对象引用的性质。
例如,假设我们有您的模块文件:
module.js
const setFn = (x) => {
module.exports.x = x;
}
module.exports = {
x: "hello",
setFn,
}
然后您将使用导出x
并在index.js中使用setFn
函数进行修改
这在这里将无法正常工作:
index.js
const {x, setFn} = require("./module");
console.log("Start"); //Start
console.log(x); //hello
setFn("world");
console.log(x); //hello - why hasn't it changed?
console.log("end"); //end
这是因为您已经向x
变量导入了直接引用,该变量在需要时具有值“ hello”。
以后当您通过setFn
函数对模块进行更改时,仍会保留对旧“ hello”值的引用。
但是,如果您将代码更改为此:
const module = require("./module");
console.log("Start"); //Start
console.log(module.x); //hello
module.setFn("world");
console.log(module.x); //world
console.log("end"); //end
然后代码起作用。
这是因为您没有导入对x
和setFn
的直接引用,而是导入了对模块本身的引用。
当您对模块本身进行突变,然后再次参考module.x
时,您可以看到更新后的值。
我还建议您查看this answer。这是关于ESM模块的,但是我认为这是相同的。
关于您正在执行的操作-我不确定这有多有用,因为要使其正常工作,确实需要模块的使用者导入整个模块,并始终通过{{1 }}。
此外,您确定要传递给module.x
函数的值不是未定义的吗?