BUG exported object won't change outside when

2019-07-25 04:07发布

File 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)   

File 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);

Assuming first random game.id is 2389423942, addPlayer method will keep adding the player to 2389423942 even after the game has finished and the id is now a different one because a new game has started. Shouldn't the replace of game in A.js replace it in B.js too? How to fix the bug?

1条回答
太酷不给撩
2楼-- · 2019-07-25 04:07

You copy only a reference of your object to function in B.js.

A fix could be to wrap the (reference to the) game object into another object and then modify that reference in there.

Replace in A.js

let game = new Game();

for example with

let game = { myGame: new Game() }

and in B.js game with game.myGame (where appropriate).

(Beside that, you use a local game variable inside Game.prototype functions. Have a look at this again. I think you got off track here...)

查看更多
登录 后发表回答