-1

我创建了一个 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));
4

1 回答 1

1

在 Javascript 函数中,数组不会被复制。如果您引用一个数组,它将始终引用同一个数组。

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

在将“卡片”数组传递给您的新对象之前,请对其进行复制:

this.assets['cards'].slice(0); //Makes a copy of your array
于 2013-07-18T19:13:10.140 回答