JavaScript范围 - 类变量的意外修改

时间:2015-12-17 03:33:13

标签: javascript

我对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;
    },
};

0 个答案:

没有答案