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

时间:2017-05-20 19:31:03

标签: 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;
   }

}

我收到以下错误:

  

无法读取未定义

的属性'getCoordinatesOfShip'

我遇到过使用相同技术的情况,即在类中调用方法并且它可以工作。

1 个答案:

答案 0 :(得分:4)

那是因为你传递给过滤器的那个函数里面的this没有绑定到类。有多种方法可以解决它。

一种是使用箭头功能,它保留了在

中定义的范围的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);
            }
        }
     });

另一个可以是先在其他变量中保留外部函数的this引用,然后在传递给过滤器的函数内部使用它 -

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

另一种方法是将该函数绑定到绑定到外部函数的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));