1

文件 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中的替换不应该也替换gameB.js中的吗?如何修复错误?

4

1 回答 1

0

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

于 2017-06-22T20:01:12.887 回答