BUG exported object won't change outside when modified

萝らか妹 提交于 2019-12-11 06:02:19

问题


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:


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



来源:https://stackoverflow.com/questions/44707490/bug-exported-object-wont-change-outside-when-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!