Javascript ES6在同一个类中的另一个方法中调用一个方法,显示我正在调用的类未定义的错误

ka2*_*2jm 2 javascript class ecmascript-6

我正在使用Javascript ES6类。我创建了一个Player类,如下所示:

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;
   }

}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

无法读取未定义的属性“ getCoordinatesOfShip”

在某些情况下,我使用相同的技术,即在类中调用方法,并且该方法有效。

Muk*_*oni 5

这是因为this您传递给filter的函数内部未绑定到该类。有多种解决方法。

一种是使用箭头功能,该功能保留了this其定义的作用域的绑定

this.ships.filter((ship) => {
        if (ship.name === shipName) {
            ship.direction = direction;
            if (ship.location.length > 0) {
                redraw = true;
                let coordinates = this.getCoordinatesOfShip(ship.name);
            }
        }
     });
Run Code Online (Sandbox Code Playgroud)

另一个方法是,首先this在其他变量中保留外部函数的引用,然后在传递给filter的函数内部使用该引用-

var self = this
this.ships.filter(function(ship) {
        if (ship.name === shipName) {
            ship.direction = direction;
            if (ship.location.length > 0) {
                redraw = true;
                let coordinates = self.getCoordinatesOfShip(ship.name);
            }
        }
     });
Run Code Online (Sandbox Code Playgroud)

还有另一种方法是将该函数this绑定到与外部函数的绑定上-

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);
            }
        }
     }.bind(this));
Run Code Online (Sandbox Code Playgroud)