我有一个扩展另一个类的类。但是,在父类中定义的函数尝试引用"this",会引发一个异常,指出"this"未定义。以下是相关代码:
class Entity {
constructor() {
this.axes = ['x', 'y'];
...
updatePosition() {
this.axes.forEach(function(axis) {
this.position[axis] += this.velocity[axis];
});
}
}
class Player extends Entity {
constructor() {
super();
....
}
...
}
var player = new Player();
并抛出错误:
.../player.js:25
this.position[axis] += this.velocity[axis];
^
TypeError: Cannot read property 'position' of undefined
您知道为什么未定义实例,以及如何修复它吗?谢谢!
在函数forEach
上下文中,this
是全局对象而不是播放器实例。由于您使用的是 ES6,因此您可以通过更改为箭头函数来解决它,如下所示:
updatePosition() {
this.axes.forEach((axis) => {
this.position[axis] += this.velocity[axis];
});
}
在"词汇这个"下阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions