2013-02-26 91 views
0

位的通用问题,但非我的情况,我不知道该怎么办,谷歌已经失败了我的少!当两个对象相互依赖时?如何去耦合他们?

我想重新写一个栅格阵列碰撞,我建画布。

现在有一个网格对象和块对象。网格cellSize取决于块size的大小相同,反之亦然。原因在于,要计算出网格数组来存储块,我必须首先计算出如何构建块,这取决于块的大小。例如,

var grid = new grid(); 

function grid() { 
    this.cellSize = 50; 
    this.cellsX = canvas.width/this.cellSize; 
    this.cellsY = canvas.height/this.cellSize; 
    this.buildGrid = function() { 
     var arr = new Array(this.cellsX); 
     for(var i = 0; i < arr.length; ++i) { 
      arr[i] = new Array(this.cellsY); 
     } 
     return arr; 
    }; 
    this.arr = this.buildGrid(); 
    this.getGridCoords = function(i) { 
     return Math.floor(i/this.cellSize); 
    }; 
} 

function block() { 
    this.size = grid.cellSize; // size of the block is same as cellSize 
    this.x = 0; 
    this.y = 0 - (this.size * 1.5); 
    this.baseVelocity = 1; 
    this.velocity = this.baseVelocity; 
    this.update = function() { 
     this.y += this.velocity; 
    }; 
} 

做它,我已经做了夫妻两个物体一起的方式,并从我percieved这是一件坏事。如果有意义,如何确保两个变量的大小相同而不耦合对象?

回答

1

真正的问题是,你的块()函数直接从电网的一个实例取一个值()。

如果你希望你的块()函数可重用和解耦,其作为改变的块()施工期间采取的大小一样简单。

arr[i] = new block({size: this.cellSize});