The following is a MCVE of my try at BattleShip in NodeJS.
Grid.set calls Grid.place which calls Grid.place.methodPlace which tries to call Grid.cells and fails. This is not the way to access such a variable, since this.cells is not in scope. What is the correct way of accessing this variable?
I'm probably making a mess of it. Beginners do that.
"use strict";
function Grid(x, y) {
var r, c, row;
this.cells = [];
this.default = " ";
for(r = 0 ; r < x ; r++) {
row = [];
for(c = 0 ; c < y ; c++) {
row.push(" ");
}
this.cells.push(row);
}
}
Grid.prototype.place = function(length) {
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var coordinateList = [];
function methodPlace(indexOfMethodToUse) {
if (indexOfMethodToUse == 0) {
var rndX = getRandomInt(0,(9-length));
var rndY = getRandomInt(0,9)
for(var i = 0 ; i <= rndX + length ; i++) {
if (this.cells[rndX+i][rndY] == this.default) { // <=====
coordinateList.push(rndX+i,rndY);
}
};
}
console.log(coordinateList);
return coordinateList;
}
methodPlace(0);
};
Grid.prototype.set = function(ac) {
for(var i = 0 ; i <= ac ; i++) {
this.place(2);
}
}
var friendlyGrid = new Grid(10,10);
friendlyGrid.set(1,2,1,1);
methodPlacea normal method, so it can accessthislikeplace()andset()can. If it's private on purpose, you need this way and you'll have to doself = thisor something to makethisaccessible in your private method. Or you can manually callmethodPlacewith this:methodPlace.call(this, 0).call()and/orselfbecause it's a normal method. If it's not private for a good reason, I'd just make it public. The.call()solution is pretty readable and short too though.