简体   繁体   中英

Why is a new instance of a object undefined?

I am unable to use the same instance of an object in another java-script file using nodejs.

I'm working on a bot for telegram. Because the file gets large and chaotic, i would like to split the functions of my bot into a few extra js files. But i don't know any way how to share the same instance of an object between multiple javascript files.

///////////////////////8Ball File
const {eightBall} = require("./main");
const ballBot = myAwseomeBot;

function eightBall() {

    ballBot.onText(/\/8ball/, (msg, callback) => {
        let ranNum = Math.floor(Math.random() * 15) + 1;
        const chatId = msg.chat.id;
        const reply_to_message_id = msg.message_id;
        console.log(ranNum);
        switch (ranNum) {
            case 1:
                ballBot.sendMessage(chatId, "Ja");
                break;
      }
    })
}


//main file

let myAwesomeBot  = new TelegramBot(botToken, {polling:true});
exports.myAwesomeBot = myAwesomeBot;










ballBot.onText(/\/8ball/, (msg, callback) => {
        ^
TypeError: Cannot read property 'onText' of undefined

Did you check that ballBot was defined? Try to remove the brackets when requiring the main file. I would also suggest using the Singleton pattern if you want to share the same instance across your code.

It isn't shown in your code here, but you probably have a cyclic dependency, where A require s B, and B require s A.

The simplest solution relevant to your use case is to define and implement commands for your bot in additional files, and let your bot file attach / consume them:

8ball.js

import { telegram stuff } from 'wherever';

export myCommand1 = {
  pattern: /\/8ball/,
  eventName: 'ontext',
  callback: (msg, msgCallback) => { /* use "this" as if it were the bot instance */};
};

main.js

import .... from ....;
import { myCommand1 } from '8ball';

...
bot.onText(myCommand1.pattern, myCommand1.callback.bind(bot));
...

There are probably other bot class methods more suited for attaching generic event handlers/listeners, and also other methods of specifying your module exports, but the idea is that your command files don't need to import the bot file. I have not researched the telegram bot API so it may have some manner of delegating the bot instance when attaching an event handler. If so, use it!

Could it be that there is a typo on line 2? Should be myAwesomeBot not myAwseomeBot.

const ballBot = myAwseomeBot;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM