2017-04-24 92 views
1

因此,我开发了一个小型游戏的基础知识...... tic tac toe ...但我遇到了一个问题,我不知道如何以最好的方式解决这个问题......所以我有这个:与Javascript对象混淆

var playfield = function(){ 
this.board = [ 
    [null, null, null], 
    [null, null, null], 
    [null, null, null] 
]; 

this.simulationMode = false; 

this.nextSymbol = "X"; 

this.setSymbol = function(symbol, x, y){ 
     if(this.whoIsNext() == symbol || this.simulationMode){ 
      if(this.isFree(x, y)){ 
       this.board[y][x] = symbol; 
       this.changeWhoIsNext(); 
       return true; 
      }else{ 
       console.log("Field is not empty "+x+";"+y); 
       return false; 
      } 
     }else{ 
      console.log("It is not "+symbol+"'s turn"); 
     } 
    }; 
... 
} 

这存储gamefield本身。

var board1 = new playfield(); 

然后我想使一个新的实例计算下一个动作:

var simboard = new playfield(); 

但后来我这样做:

simboard.setSymbol("X", x, y); 

它使委员会1和simboard的变化。 为什么?我做错了什么...?

完整的源可以在这里找到: https://gameink.net/js/tictactoe.js?PageSpeed=off

+1

您对“this.board”属性的引用有问题。你用不同的方式初始化它。例如,创建对象的新实例时。 – sunpietro

+0

另外,不是'new new'抛出一个错误? – evolutionxbox

+0

好点,是一个复制粘贴错字。 –

回答

0

这是因为JavaScript对象引用

试试这个

playfield.prototype = Object.create(playfield.prototype); 

所以每当你将这个所以它会在每次使用新实例。

+1

请您详细解释一下。 –