When I create an array of classes in JavaScript, editing one affects all other created objects in the array. I'm on node version 8.11.4.
I tried using the .push() method to send an update to the array but it still affected every object in the array instead of just the one that was intended.
This is the class that the objects of the array are. Tile.js
let isObstacle;
class Tile {
constructor(){
isObstacle = false;
}
setObstacle() {
isObstacle = true;
}
getObstacleStatus() {
return isObstacle;
}
}
module.exports = Tile;
This is the second class where the array of Tile objects is. Test.js
const Tile = require('./Tile');
let g = [];
//g[0] = new Tile();
//g[1] = new Tile();
g.push(new Tile());
g.push(new Tile());
console.log(g[0].getObstacleStatus());
console.log(g[1].getObstacleStatus());
//g[0].setObstacle();
g.push(g[0].setObstacle());
console.log(g[0].getObstacleStatus());
console.log(g[1].getObstacleStatus());
The expected results are:
false false
true false
The actual results are:
false false
true true
The g[0].setObstacle(); is supposed to only set the g[0] instance of isObstacle to true but instead it sets both g[0] and g[1] to true.
let isObstacleis external to the class instance. Declare it as an instance property instead.