【问题标题】:BUG exported object won't change outside when modifiedBUG 导出的对象修改后不会在外面改变
【发布时间】:2017-06-22 19:05:50
【问题描述】:

文件 A.js

function Game() {
this.id = Math.random();
this.endTimeout = setTimeout(() => {
    this.end(this);
    return
}, this.duration * 60 * 1000);
}
Game.prototype.addPlayer = function(game, player, items) {
        console.log('addPlayer to game.id ' + game.id)
        if (game.totalItemAmount >= 50) {
            clearTimeout(game.endTimeout)
            game.end(game);
        }
        return
    }
Game.prototype.end = function(game) {
game = new Game();
}

let game = new Game();
require('../../tests/B.js')(game)   

文件 B.js

  module.exports = function (game) { 

    let test = setInterval(() => {
    for (var i = 0; i < 10; i++) {
           game.addPlayer(game, {
                playerID: '2134' + i,
                nickname: "player" + i

            },
    }, 4000);

假设第一个随机 game.id 是 2389423942,addPlayer 方法将继续将玩家添加到 2389423942,即使在游戏结束之后,由于新游戏已经开始,id 现在是不同的了。 A.js 中game 的替换不应该也替换B.js 中的吗?如何修复这个错误?

【问题讨论】:

    标签: javascript node.js modular-design


    【解决方案1】:

    您仅复制对象的引用以在 B.js 中运行。

    解决方法可能是将(对该游戏对象的引用)包装到另一个对象中,然后在其中修改该引用。

    替换为A.js

    let game = new Game();
    

    例如

    let game = { myGame: new Game() }
    

    B.js gamegame.myGame 中(如果适用)。

    (除此之外,您在Game.prototype 函数中使用了本地game 变量。再看看this。我认为您在这里偏离了轨道......)

    【讨论】:

    • { myGame: new Game() } 将允许我将玩家添加到不同的游戏 ID,或者它会在我每次添加玩家时创建游戏 ¬¬?请告诉我你将如何在没有本地参考的情况下结束这个游戏(在结束游戏中 = this)
    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 2020-01-02
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2013-11-23
    相关资源
    最近更新 更多