1

I've got 2d array of object like chessboard.

You can get object by data.field(x,y); (object are stored inside 2d array of objects)

I want each of fields to have functions: top, bottom, left, right that will return neighbour field.

For example data.field(3,3).top().left().bottom().name would return name of field(4,3).

But: Have I to declare those function for each of objects? I mean, for example on 8x8 field that would be 64 instances of the same function:

data.field(0,0).top = function(){...}
data.field(0,1).top = function(){...}
...

Ofc I can easily declare them inside loop, but its pure waste of memory and I'm sure its not the way to do it. Is it possible to declare this functions only once to be available inside every object returned by field(x,y) function?

2 Answers 2

1

Is it possible to declare this functions only once to be avaliable inside every object returned by field(x,y) function?

Absolutely:

function top() {
    // ...do your thing, using `this`
}

data.field(0,0).top = top;

When top is called as part of an expression retrieving it from the field(0,0) object, within the call to top, this will be the field(0,0) object. And similarly for field(0,1), etc.

More (on my blog):

Now, that assumes that for whatever reason, you already have the field(0,0) and such objects (perhaps they're created by code you don't control). If you control the code, you can do this via the prototype chain instead:

function Field() {
}
Field.prototype.top = function() {
    // ...do your top thing, using `this`
};

...and when creating your fields:

yourField = new Field();

So it depends on what data.fields(0,0) is and where you get it.

Sign up to request clarification or add additional context in comments.

4 Comments

@alex23: What's not OOP about attaching behaviors to objects?
Do I need to still do it for each of fields? data.field(0,0).top = top; data(0,1).top = top and so on?
@OPOPO: You do with the above, let me post an alternative. But note that although you're doing the assignment, you're not duplicating the function, you're just reusing it.
@alex23 you can do OOP without Classes, even without prototypes because JavaScript is that awesome.
0

If you want to conserve memory you should look at prototypes. They're like Classes in Object Oriented languages, so there is an opportunity for memory optimization.

var Field = function() {}; // this is your constructor
Field.prototype.top = function () { /* .. */
    return this; // return the field so you can do chaining: field.top().left();
};
Field.prototype.left = function () { /* .. */
    return this;
};
/* .. */
var field = new Field();
data.set(0, 0, field);
data.field(0, 0).top().left();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.