Ideally I would like to do something like the following:
class Chess = {
constructor() {
this.board = ...;
...
};
class Square = {
constructor(row, col) {
this.row = row;
this.col = col;
};
};
My main motivation is that with the Chess and Square classes defined separately something like: (this referring to the Chess class)
this.empty(square)
could be shortened to
square.empty()
which is more readable and more concise.
Unfortunately I can't just make a
Square.empty()
method since the results depends on the information in the Chess class and
square.empty(chess)
is no real improvement.
The reason I have a Square class is that something like
square.up()
seems much nicer than something like
[row, col + 1]
Do you have a suggestion on how I would accomplish the above? Some way to write a class within a class or something else entirely?
EDIT:
Following the advice from likle and alex I did the following:
I added a context property to the Class Square
class Square = {
constructor(context, row, col) {
this.context = context;
this.row = row;
this.col = col;
};
};
Then redefined some methods from the Chess.prototype to the Square.protoype. For example:
// before
Chess.prototype.empty = function (square) {
return this.piece(square) === 0;
};
// after
Square.prototype.empty = function () {
return this.piece() === 0;
};
Which meant that every time I created a Square object I need to add context. For example:
new Square(3, 4); // before
new Square(this, 3, 4); // after
new Square(this.context, 3, 4); // sometimes like this
To make the code more readable I created the following method:
Chess.prototype.createSquare = function (row, col) {
return new Square(this, row, col);
};
So a Square object can sometimes be created with
this.createSquare(3, 4);