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”
在某些情况下,我使用相同的技术,即在类中调用方法,并且该方法有效。
这是因为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)
归档时间: |
|
查看次数: |
1894 次 |
最近记录: |