I want to build a grid and I have 2 concepts: Grid
which is consist of Cell
.
Grid class is:
var Grid = function (rows, columns, cellInit) {
var canvas = create_canvas();
this.context = canvas.getContext('2d');
this.matrix = new Array(rows);
for (var x = 0; x < rows; x+=1) {
this.matrix[x] = new Array(columns);
for (var y = 0; y < columns; y+=1) {
this.matrix[x][y] = new Cell(x, y, cellInit(), this.context);
}
}
};
Cell class is:
var Cell = function (x, y, value, context) {
this.x = x;
this.y = y;
this.rectX = s.cell_width * this.x + s.pad;
this.rectY = s.cell_height * this.y + s.pad;
this.value = value;
this.context = context;
};
Also I have fill
method for Cell
:
Cell.prototype.fill = function(type) {
this.context.fillStyle = s.colors[type];
this.context.fillRect(this.rectX, this.rectY, s.rect_width, s.rect_height);
return this;
}
And actually I have 2 questions about this code:
- Looks like that
Grid
andCell
should have parent-child relationship. Is it normal that I'm creating child objects at parent class? - I need somehow to give access to context var from
Cell
class without passing it via constructor. I had tried to play with prototypes but can't figure out how to do that.