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