I'm confused by the following scoping in JavaScript. I have a global object Rummy
to which I then attach a Manager
object.
The confusion is in calculate
, where I store the player's current cards in a local variable var cards
. I push a card into cards
, but somehow this modifies the total cards in this.current_player.cards
.
Why is this?
(function () {
window.Rummy = window.Rummy || {};
})();
(function () {
Rummy.Manager = Rummy.Manager || {};
Rummy.Manager = (function () {
var api = {},
api.init = function () {
this.players = createPlayers();
this.current_player = this.players.mainPlayer;
this.deck = [//some card objects in here];
this.calculate(this.deck[this.deck.length-1]);
};
api.calculate = function (card) {
// Create a new variable to store player's cards as to not modify the player's current cards...
var cards = this.current_player.getCards();
console.log('A: total cards', this.current_player.getCards());
cards.push(card);
console.log('B: total cards', this.current_player.getCards());
};
return api;
})();
})();
(function () {
Rummy.Manager.init();
})();
this.current_player.getCards();
initial total: 7
A's output: 8 cards
B's output: 8 cards
If I comment out cards.push(AI_card);
:
A's output: 7 cards
B's output: 7 cards
If I'm declared var cards
and only modifying the new array, why is it changing the player's cards array?
Player Class if needed:
var Player = function(manager, canvas, args) {
this.cards = [];
...
};
Player.prototype = {
constructor: Player,
setCards : function (card) {
this.cards.push(card);
},
getCards : function () {
return this.cards;
},
};