【问题标题】:When two objects are dependent on each other? How to de-couple them?当两个对象相互依赖时?如何解耦它们?
【发布时间】:2013-02-26 07:32:34
【问题描述】:

有点笼统的问题,但我不知道该怎么做,谷歌让我失望了!

我正在尝试用我构建的画布重写网格数组冲突。

现在有一个网格对象和一个块对象。网格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;
    };
}

按照我的做法将两个对象耦合在一起,据我所知,这是一件坏事。如果有意义,我如何确保这两个变量的大小相同而不耦合对象?

【问题讨论】:

    标签: javascript object decoupling


    【解决方案1】:

    真正的问题是您的 block() 函数直接从 grid() 的实例中获取值。

    如果您希望您的 block() 函数可重用和解耦,它就像在构造期间更改 block() 以获取大小一样简单。

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

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      相关资源
      最近更新 更多