OPOPO
OPOPO

Reputation: 503

JS - Same function in each object in array

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?

Upvotes: 1

Views: 79

Answers (2)

Halcyon
Halcyon

Reputation: 57719

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();

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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.

Upvotes: 1

Related Questions