I am building a chess application and am running into an issue about the difference between object definition and instantiation in JavaScript. For example, I want to separate my Board
model (and view) from its representation (a nested array) via a Matrix
model:
var Matrix = function(n, m) {
// builds an n*m nested array
// e.g. a 2x3 array would look like this:
// [[0, 0], [0, 0], [0, 0]]
};
// A setter, which takes a `Point` object and correctly updates the nested array
Matrix.prototype.set = function(pt, obj) {
this.state[pt.y][pt.x] = obj;
};
// A custom `each` method that iterates over the nested array
Matrix.prototype.each = function(fn) {
// executes `fn` against every (x,y) in the nested array
};
// etc.
And then Board
looks like this:
var Board = function(n, m) {
Matrix.call(this, n, m);
// now use `Matrix`'s `set` method to place pieces on the board.
};
Board.prototype = Matrix.prototype;
// etc.
My issue is really in the definition of Board
. When I instantiate a new Board
object, I would like for it to subclass Matrix
and then use Matrix
's methods to set pieces on the board. But the problem is that Board
does not have access to Matrix
's methods at instantiation, because that relationship is still being defined.
Trying to resolve this issue has clarified the answer to this question. It seems like the problem is that Board
isn't a real subclass of Matrix
. That relationship is not set until the code actually executes. What is the JavaScript-esque way of handling this relationship?