我对JavaScript中的以下范围感到困惑。我有一个全局对象Rummy
,然后我附加一个Manager
对象。
混淆在calculate
,我将玩家当前的牌存储在本地变量var cards
中。我将卡片推入cards
,但不知怎的,这会修改this.current_player.cards
中的总卡数。
为什么会这样?
(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();
初始总数:7
A's output: 8 cards
B's output: 8 cards
如果我发表评论cards.push(AI_card);
:
A's output: 7 cards
B's output: 7 cards
如果我宣布var cards
并且只修改新阵列,为什么要改变玩家的牌阵列?
玩家类:
var Player = function(manager, canvas, args) {
this.cards = [];
...
};
Player.prototype = {
constructor: Player,
setCards : function (card) {
this.cards.push(card);
},
getCards : function () {
return this.cards;
},
};