javascript - 未捕获的 TypeError 不是函数类方法
问题描述
我是 JavaScript 新手,我收到此错误:
Uncaught TypeError: this.move is not a function
如果我的问题主要是代码,那么不会让我发帖,所以这里是 github 中文件的链接: https ://github.com/pianocomposer321/Dodger.js/blob/master/player.js
错误发生在onKeyPressed
函数中的第一个 case 语句尝试调用时this.move()
。
class Player {
constructor(width, height, cvs) {
this.width = width;
this.height = height;
this.cvs = cvs;
this.ctx = this.cvs.getContext("2d");
this.x = this.cvs.width / 2;
this.y = this.cvs.height - this.height;
document.addEventListener("keydown", this.onKeyPressed);
}
draw() {
this.ctx.fillRect(this.x, this.y, this.width, this.height);
}
move(x, y) {
this.x += x;
this.y += y;
}
onKeyPressed() {
switch (window.event.keyCode) {
case 37:
this.move(-5, 0);
break;
case 38:
this.move(0, 5);
break;
case 39:
this.move(5, 0);
break;
case 40:
this.move(0, -5);
break;
}
}
}
export { Player };
提前致谢!
解决方案
addevent 监听器正在改变这一点。您需要使用绑定。
class Player {
constructor(width, height, cvs) {
this.x = 0;
this.y = 0;
document.addEventListener("keydown", this.onKeyPressed.bind(this));
}
move(x, y) {
this.x += x;
this.y += y;
console.log(this.x, this.y);
}
onKeyPressed() {
switch (window.event.keyCode) {
case 37:
this.move(-5, 0);
break;
case 38:
this.move(0, 5);
break;
case 39:
this.move(5, 0);
break;
case 40:
this.move(0, -5);
break;
}
}
}
new Player()
推荐阅读
- css - 媒体查询中窗口屏幕的实际大小
- node.js - 使用 JSON.stringify 字符串化的符号
- python - 更改 pandas 数据框中的行顺序而不会丢失或弄乱数据
- windows-10 - 自定义凭据提供程序:未显示在登录屏幕上的登录用户
- in-app-purchase - 是否有必要从“Google Play Billing with AIDL”迁移到“Google Play Billing Library”?
- javascript - 修改扩展Vue组件的mounted()钩子
- c# - 如何在 EF 上启用身份插入 - 代码首先是 context.Seed(),然后在数据播种后再次禁用
- wordpress - 合并网站、图片双ID问题
- wicket - 如何在 Wicket 中从 tinyMCE 设置宽度
- go - 无法在 Go 应用程序的另一个包中使用函数