I am building a factory function to manage Ship objects for a battleship game. So far I have the following:
const Ship = (name, length, orientation = 'horizontal') => {
let sunk = false;
const hits = Array(length).fill(false);
const hit = (position) => {
if (position <= hits.length) hits[position] = true;
};
function sink() {
sunk = true;
}
return {
name,
length,
orientation,
sunk,
hits,
hit,
sink,
};
};
I am testing the sink() method to change the sunk property boolean from false to true. However, whenever I run:
example.sink()
example.sunk
sunk always remains false.
Where am I going wrong?
For some reason the hit() method alters the hits propertyfine. Butsink()is not altering thesunk` property.
Thanks
sunkis a boolean value, not an array ref likehits. The object returned byShipisn't re-evaluated, so the value will always be the same.getterandsetterforsunkproperty.