【问题标题】:How can I use a variable globally in js (across many files)?如何在 js 中全局使用变量(跨多个文件)?
【发布时间】:2020-07-30 23:01:45
【问题描述】:

我有以下问题:我正在使用 discord.js 编写一个机器人,而且我是 JavaScript 新手。我想有 2 个变量,给它们一个占位符值,然后更改一个命令文件中的值,并能够读取不同命令文件中的值。基本上,我希望能够在许多不同的 JavaScript 文件中声明变量、更改和读取它们的值。我的代码在下面!

index.js

const fs = require("fs");
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");

const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

let target;
let targetName;
global.target;
global.targetName;

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once("ready", () => {
    console.log("Ready!");
});

client.on("message", message => {
    console.log(`<${message.author.tag}> ${message.content}`);
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    try {
        target, targetName = client.commands.get(command).execute(message, args, target, targetName);
    }
    catch (error) {
        console.error(error);
        message.reply("there was an error trying to execute that command!");
    }

});

client.login(token);

target.js

module.exports = {
    name: "target",
    description: "Targets the user(s) that the operator wants to trigger.",
    // execute(message, args) {
    execute(message, target, targetName) {
        if (message.member.roles.cache.has("737693607737163796") == true) {

            //  This will check if there are any users tagged. if not, the author will be targeted.
            if (!message.mentions.users.size) {
                message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${message.author.tag}sama*\n**__Armed and loaded, M-master__**`);
                target = (message.author.id);
                targetName = (message.author.tag);
                message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);
                return target, targetName;
            }

            // grab the "first" mentioned user from the message
            // this will return a `User` object, just like `message.author`
            const taggedUser = message.mentions.users.first();

            message.reply(`Y-yes, Ssenpai :pleading_face:\n*points gun at @${taggedUser.tag}san*\n**__Armed and loaded, M-master`);
            target = (taggedUser.id);
            targetName = (taggedUser.tag);
            message.reply(`N-new *QwQ* new ttarget's s-snowflake: ${target} (t-target is-s: ${targetName})`);

            console.log(`Target has changed! New target ID: ${target} New target name: ${targetName}`);
            return(target, targetName);
        }
        else {
            console.log("User isn't admin or there was an error executing the command!");
            message.reply("You don't have OP permissions! Only users with OP permissions are allowed to execute that command!");
        }
    },
};

targetCheck.js

module.exports = {
    name: "targetcheck",
    description: "Check for the current target!",
    // execute(message, args) {
    execute(message, target, targetName) {
        message.reply(`The current target is: ${targetName}(${target})`);
    },
};

【问题讨论】:

  • 您可以使用global object
  • @jonatjano 你的意思是 global.target 和 global.targetName 吗?
  • 是的,这正是我的意思
  • 把我的评论变成了答案
  • 你不应该使用 target 和 global.target 你应该只使用 global.target

标签: javascript node.js discord.js


【解决方案1】:

由于您使用的是NodeJS,因此您应该使用global object

在您设置的一个文件中

global.someAttributeName = "some value"

现在可以从任何地方访问它

console.log(global.someAttributeName)
// logs : some value

【讨论】:

    【解决方案2】:

    你可以在你的项目中使用库作为 redux 来获得全局状态:https://redux.js.org/ 我想你也可以使用全局 Node.js https://nodejs.org/api/globals.html#globals_global

    【讨论】:

    • 我用的是后者,可能是我用错了..let target; let targetName; global.target; global.targetName;
    猜你喜欢
    • 2011-02-25
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多