G
G
getaxe2022-03-05 16:43:37
JavaScript
getaxe, 2022-03-05 16:43:37

How to create your file with functions?

In general, I’m not good at browsing the Internet, apparently, I’ve surfed all over, but I didn’t find what I needed.
I managed to do what I wanted, but not completely.
What I have:

//в main.js
bot.func = require('./functions'); //должно писаться именно так, ибо переменная бот летает по всему коду. 

//в /functions/index.js
function getMemoryMember (bot, id) {
   //1412351235
}
function getGuildMember (bot, id) {
     //1412351235
}
function addExp (bot, id, exp) {
     //1412351235
}
function getGuildRole (bot, id) {
    //1412351235
}
function declOfNum(n, text_forms) {  
     //1412351235
}
function getTime (time) {
     //1412351235
}

module.exports = {
    getMemoryMember: getMemoryMember,
    getGuildMember: getGuildMember,
    addExp: addExp,
    getGuildRole: getGuildRole,
    declOfNum: declOfNum,
    getTime: getTime
};

With this code, I can easily access bot.func "function name" in all files and everything is fine. But I really don't like that the bot variable is not passed here, and I have to pass it when using the function.
About what I want:
//в main.js 
bot.func = require('./functions')(bot);

//в /functions/index.js
module.exports = (bot) => {
function getMemoryMember (bot, id) {
   //1412351235
}

As I understand it, with this syntax, require itself becomes a function and cannot pass something from itself. How do I get it right so that the bot goes there with require.
ps I've already read 15 articles about functions, require, and exports =/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2022-03-05
@getaxe

Well, for example, like this, if you do not change the definition of functions:

//в main.js 
bot.func = require('./functions')(bot);

//в /functions/index.js
module.exports = (bot) => ({
    getMemoryMember: (id) => getMemoryMember(bot, id),
    getGuildMember: (id) => getGuildMember(bot, id),
    ...
    declOfNum,
    getTime,
});

Although I could just add them directly to the bot and use this.
// в main.js
Object.assign(bot, require('./functions'));

// вместо bot.func.getMemoryMember(bot, id)
bot.getMemoryMember(id);

//в /functions/index.js
function getMemoryMember (id) {
   // тут использовать this вместо bot
}
function getGuildMember (id) {
     //1412351235
}
...

module.exports = {
    getMemoryMember,
    getGuildMember,
    addExp,
    getGuildRole,
    declOfNum,
    getTime
};

Or maybe you even need to add it to the bot prototype, but you already need to look at how the bot and its prototype are defined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question