Javascript OOP-多个实例共享相同的数据
我创建了一个javascript类。当我使用Javascript OOP-多个实例共享相同的数据,javascript,Javascript,我创建了一个javascript类。当我使用new关键字创建实例时,我不知道为什么所有实例都共享相同的数组数据 有人能解释为什么会这样吗?本例中的卡数组由我创建的所有实例引用: (function (scope) { //Player class: player information, graphics object //Contructor: init properties function Player(opts) { //INITIALIZE PR
new
关键字创建实例时,我不知道为什么所有实例都共享相同的数组数据
有人能解释为什么会这样吗?本例中的卡
数组由我创建的所有实例引用:
(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));
在Javascript函数中,数组不会被复制。如果引用一个数组,它将始终引用同一个数组 如果不想传递对同一数组的引用,则必须将值复制到新数组。如果数组只包含字符串,这可能很简单;如果数组包含其他数组或对象,则它也可能很复杂 在将“卡片”数组传递给新对象之前,复制一份该数组:
this.assets['cards'].slice(0); //Makes a copy of your array
虽然JavaScript是一种OO语言,但它并没有真正的类。JavaScript的可能副本有伪类。它们做了类所做的事情,但仍然不是类@弥赛亚:我能问一下js有什么不同的功能可以让你说它有类吗?将“Cards:[],”改为“this.Cards=[]”,并将其移动到构造函数中。。。是一个不同的概念(用于函数调用),请不要在这里使用该术语。“传递引用”听起来更好:-)根据您的建议进行编辑。我已经知道了,但我认为当我使用new关键字创建对象时,将创建新对象和所有属性?您在问题中提到“cards”数组被所有实例引用。这并不意味着所有卡实例都是相同的。您可以根据需要创建任意多个新对象,但如果将同一数组传递给它们,它们将全部引用同一数组。