Javascript OOP - 多个实例共享相同的数据

时间:2013-07-18 19:07:50

标签: javascript

我创建了一个javascript类。当我使用new关键字创建实例时,我不知道为什么所有实例共享相同的数组数据。

有人可以解释为什么会这样吗?我创建的所有实例都引用了此示例中的Cards数组:

(function (scope) {
    //Player class: player information, graphics object
    //Contructor: init properties
    function Player(opts) {
        //INITIALIZE PROPERTIES
        this.initialize(opts);
    }

    Player.prototype = {
        AccountID: '',
        Position: -1,
        UserName: '',
        Level: 0,
        Avatar: 'av9',
        Gold: 0,
        Cards: [],
        pos: { x: 0, y: 0 },
        graphicsObj: {},
        assets: {},
        Status: 0,

        initialize: function (opts) {
            //copy all properties to new instance       
            this.copyProp(opts);

            this.setCards();
            this.createGraphicObject();
        },

        //copy properties to instance
        copyProp: function (opts) {
            for (var prop in opts) {
                this[prop] = opts[prop];
            }
        },

        ... 
        ...

        setCards: function () {
            //create new Cards data with default position
            this.Cards[0] = new scope.Card({ image: this.assets['cards'] });
            this.Cards[1] = new scope.Card({ image: this.assets['cards'] });
            this.Cards[2] = new scope.Card({ image: this.assets['cards'] });
        }
    };

    scope.Player = Player;
}(window));

1 个答案:

答案 0 :(得分:1)

在Javascript函数中,不会复制数组。如果引用数组,它将始终引用相同的数组。

如果您不想将引用传递给同一个数组,则必须将值复制到新数组。如果数组只包含字符串,这可能很简单;如果数组包含其他数组或对象,它也可能很复杂。

在将“牌”数组传递给新对象之前制作一份副本:

this.assets['cards'].slice(0); //Makes a copy of your array