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?
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
for example with
and in
B.js
game
withgame.myGame
(where appropriate).(Beside that, you use a local
game
variable insideGame.prototype
functions. Have a look atthis
again. I think you got off track here...)