0

所以我试图保持我的代码干净。为此,我使用了 VS 代码的内置代码重构“移动到新文件”。与往常一样,它不可能那么容易,所以一切都不起作用。当我尝试在我的 Game 类中使用此方法时,我收到一条错误消息getRandomInt is not a function. 我已经看到了十几个关于这个的 StackOverflow 线程,尽管它们都不能解决我的问题。然后我认为这可能只是个人问题,所以我在这里。被同样的问题困扰了两天...

游戏.js:


const { getRandomInt } = require("./index.js");

class Game {
    /**
     *
     * @param {Discord.Message} message
     * Passes the message object for the playerId that will be the game Id
     */
    constructor(message) {
        this.cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
        this.playerId = message.author.id;
        this.dealerCards = [];
        this.playerCards = [];
        this.message = message;
    }

    start() {
        console.log(this.cards);
        for (let index = 0; index < 2; index++) {
            this.playerCards.push(this.cards[getRandomInt(1, this.cards.length)]); 
            //There's an error saying that getRandomInt is not a function
            this.dealerCards.push(this.cards[getRandomInt(1, this.cards.length)]);

        }
        console.log(this.playerCards);
        console.log(this.dealerCards);
        this.message.channel.send(`Dealer cards: ${this.dealerCards[0]} ${this.dealerCards[1]}\nPlayer cards ${this.playerCards[0]} ${this.playerCards[1]}`);

    }

    hit() {
        this.playerCards.push(this.cards[getRandomInt(1, this.cards.length)]);

    }
}
exports.Game = Game;

index.js (有点减少,但它不应该有所作为):

const { Game } = require("./Game.js");

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
}
exports.getRandomInt = getRandomInt;

有那么难吗?它内置在 VS 代码的重构系统中,所以我觉得有些东西在我身上。

4

1 回答 1

3

循环依赖问题。我不知道您为什么需要Game.jsindex.js文件中导入,但删除它会解决问题。如果您仍想Game.js在您的中使用index.js,有一些方法适合您:

  • 制作一个空的模块导出。例如:将exports.Game = function(){};exports.getRandomInt = function(){};放在模块的开头。这种方法可以解决您的问题取决于您的逻辑,您最好提供有关代码的更多详细信息以了解您的真正问题。
  • 重构你的代码。

更多信息:

如何处理 Node.js 中的循环依赖

https://nodejs.org/api/modules.html#modules_cycles

于 2020-11-28T19:13:43.957 回答