简体   繁体   English

为什么该对象返回相同的设置?

[英]Why does this object return same settings?

I have a Game class that initializes player objects. 我有一个Game类,用于初始化玩家对象。 I'm initializing two players p1 and p2 . 我正在初始化两个玩家p1p2 Yet when I console log them, they return the same settings, even though I'm setting p2 's color to #000 . 但是,当我用控制台登录它们时,即使我将p2的颜色设置为#000 ,它们也会返回相同的设置。

What's the problem? 有什么问题?

I've tried this.p1.color and this.p1['color'] 我已经尝试过this.p1.colorthis.p1['color']

var Game = {
players: 2,
p1: {},
p2: {},
currentPlayer: 1,

initPlayers: function(){
    this.p1 = Player;
    this.p2 = Player;
    this.p1.credits = 500;
    this.p2.credits = 800;
    this.p1['color'] = '#3e3e3e';
    this.p2['color'] = '#000';
    console.log(this.p1);
    console.log(this.p2);
}

}

 var g = Game;
 g.initPlayers();

Console.log is showing Console.log正在显示

 Object {credits: 800, moves: Array[0], color:'#000', getMoves: function, checkPlayer: function, enterMove: function…}
 Object {credits: 800, moves: Array[0], color:'#000', getMoves: function, checkPlayer: function, enterMove: function…}

Even though I'm setting them separately above. 即使我在上面分别设置了它们。

Clearly the setting of the values is working, both with brackets and dot notation, however, it's as if only the final values make it. 显然,使用括号和点表示法都可以使用这些值的设置,但是,好像只有最终值才能使用它。 And copy to both p1 and p2 . 并复制到p1p2

Am I missing something super obvious? 我是否缺少一些明显的东西?

When you set 设置时

this.p1 = Player;
this.p2 = Player;

You make both variables hold the same object. 您使两个变量都持有同一个对象。 I'm not sure of what you want so here are two hypothesis : 我不确定您要什么,因此有两个假设:

1) If you want to have separate copies of the Player object, you should clone them, for example like this (for a non deep cloning) : 1)如果要拥有Player对象的单独副本,则应克隆它们,例如,如下所示(用于非深度克隆):

this.p1 = {};
this.p2 = {};
for (var k in Player) {
   this.p1[k] = Player[k];
   this.p2[k] = Player[k];
}

2) If Player is a class, as the capitalized name would suggest, then what you need is an instanciation, which is done using new : 2)如果Player是一类,如大写的名字所示,那么您需要的是实例化,可以使用new来完成:

this.p1 = new Player();
this.p2 = new Player();

In JavaScript when you assigning something to an object (eg this.p1 = Player ), you don't create new object, but only link to the existing one. 在JavaScript中,当您向对象分配某些内容(例如this.p1 = Player )时,您不会创建新对象,而只会链接到现有对象。 You'll need to create a fresh object, using Player as prototype: 您需要使用Player作为原型创建一个新的对象:

this.p1 = Object.create(Player);
this.p2 = Object.create(Player);

Similarly, when you create new game you, better use Object.create() if you want to have more than one: 同样,在创建新游戏时,如果要拥有多个游戏,最好使用Object.create()

var g = Object.create(Game);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM