以两种不同的方式将函数传递给 module.exports

时间:2021-04-09 13:45:57

标签: javascript

我正在开发一个 Discord 机器人,并且想要一个包含一些有用函数的 js 文件,以便在所有其他文件中使用。我在 global.js 文件中使用 module.exports 并要求在其他文件中使用该文件。

我发现,如果我以一种方式这样做,它会起作用,但在另一种方式中,我认为这应该是同一件事,却不会。

这有效:

module.exports.commandMessage = async(message, commandArgs) => {
    message.reply(`This is a test, it should work, maybe. Who knows? I hope.\n ${commandArgs._}`)
        .then(msg => {
            msg.delete({ timeout: 3000 })
        })
        .catch(console.error)
}

这不会:

const commandMessage = async(message, commandArgs) => {
    message.reply(`This is a test, it should work, maybe. Who knows? I hope.\n ${commandArgs._}`)
        .then(msg => {
            msg.delete({ timeout: 3000 })
        })
        .catch(console.error)
}

module.exports.functions = commandMessage // Hoping to make this an array of functions

它抛出

TypeError: global.commandMessage is not a function

这就是我调用函数的方式

const global = require('../global.js')

module.exports = {
    aliases: ['test'],
    event: 'message'
}
module.exports.command = async(message, commandArgs) => {
    global.commandMessage(message, commandArgs) // or global.functions.commandMessage(...)
}

我知道我可以简单地使用有效的版本,我会这样做。这个问题纯粹是学术性的。

0 个答案:

没有答案