1

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.

1
  • let isObstacle is external to the class instance. Declare it as an instance property instead. Commented Apr 28, 2019 at 18:41

1 Answer 1

3

What you are doing is a class that is modifying a global variable called, isObstacle. you are declaring that variable outside your class.

just declare isObstacle as an attribute of your class.

class Tile {
  constructor() {
    this.isObstacle = false;
  }

  setObstacle() {
    this.isObstacle = true;
  }

  getObstacleStatus() {
    return this.isObstacle;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.