Rob
Rob

Reputation: 59

How can I fix this "reference grid" of objects done in JavaScript?

I am attempting to make a 3x3 grid of "block" objects in JavaScript, each of which contains a reference to the blocks next to it through 4 directional parameters "below," "left," "above," and "right." The problem is due to the nature of JavaScript's object construction, I get a lot of undefined "block" references in the first blocks to be defined.

Here is a visualization of what I am trying to accomplish:

    [00][01][02]
    [10][11][12]
    [20][21][22]

Here is my code:

    // Block variable declarations

    var block00;
    var block01;
    var block02;

    var block10;
    var block11;
    var block12;

    var block20;
    var block21;
    var block22;

    // Block object constructor

    function block(below, left, above, right){
        this.below = below;
        this.left = left;
        this.above = above;
        this.right = right;
    }

    // Row 1

    block00 = new block(block10, null, null, block01);
    block01 = new block(block11, block00, null, block02);
    block02 = new block(block12, block01, null, null);

    // Row 2

    block10 = new block(block20, null, block00, block11);
    block11 = new block(block21, block10, block01, block12);
    block12 = new block(block22, block11, block02, null);

    // Row 3

    block20 = new block(null, null, block10, block21);
    block21 = new block(null, block20, block11, block22;
    block22 = new block(null, block21, block12, null);

So, for example, calling

    block00.below

will return an undefined value, but I want it to return block10.

Thanks!

Upvotes: 1

Views: 91

Answers (1)

Bergi
Bergi

Reputation: 665256

You'll need to construct the objects before you assign reference to them. There's no way around that.

An easy way to do that is to remove the below and right parameters from your constructor, and set those fields dynamically when that block is constructed:

function block(left, above) {
    this.below = null;
    this.left = left;
    this.above = above;
    this.right = null;

    if (left) left.right = this;
    if (above) above.below = this;
}

Upvotes: 1

Related Questions