Javascript ES6 calling a method inside another method within the same class shows an error the class i am calling is undefined

Viewed 4652

I am using Javascript ES6 classes. I have created a Player class as below:

class Player {

  constructor() {
     .....
     .....
  }
  changeShipDirection(shipName, direction) {
    let redraw = false;
    this.ships.filter(function(ship) {
        if (ship.name === shipName) {
            ship.direction = direction;
            if (ship.location.length > 0) {
                redraw = true;
                let coordinates = this.getCoordinatesOfShip(ship.name);
            }
        }
     });

     return redraw
   }

   getCoordinatesOfShip(shipName) {
      let coordinates = [];
      this.ships.filter(function(ship) {
          if (ship.name === shipName) {
              coordinates = ship.location;
          }
      });

      return coordinates;
   }

}

I get the following error:

Cannot read property 'getCoordinatesOfShip' of undefined

I have cases where I use the same technique i.e. calling a method within the class and it works.

1 Answers
Related