Javascript 当两个对象相互依赖时?如何将它们分离?
这是一个普通的问题,但我不知道该怎么办,谷歌让我失望了 我正试图用我构建的画布重新编写一个网格数组冲突 现在有一个栅格对象和一个块对象。网格Javascript 当两个对象相互依赖时?如何将它们分离?,javascript,object,decoupling,Javascript,Object,Decoupling,这是一个普通的问题,但我不知道该怎么办,谷歌让我失望了 我正试图用我构建的画布重新编写一个网格数组冲突 现在有一个栅格对象和一个块对象。网格cellSize取决于块size的大小,反之亦然。原因是,要计算出存储块的网格阵列,我必须首先计算出如何构建它,这取决于块的大小。例如 var grid = new grid(); function grid() { this.cellSize = 50; this.cellsX = canvas.width / this.cellSize
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;
};
}
var grid=new grid();
功能网格(){
这个。细胞大小=50;
this.cellsX=canvas.width/this.cellSize;
this.cellsY=canvas.height/this.cellSize;
this.buildGrid=函数(){
var arr=新数组(this.cellsX);
对于(变量i=0;i
以我的方式将两个物体连接在一起,从我的感受来看,这是一件坏事。如果有意义,如何确保两个变量大小相同而不耦合对象?真正的问题是block()函数直接从grid()的实例中获取值 如果希望block()函数可以重用和解耦,那么在构造过程中更改block()的大小就很容易了
arr[i] = new block({size: this.cellSize});