javascript - js -Uncaught TypeError:无法读取对象未定义的属性“x”(球
问题描述
您好,我在尝试运行此代码时收到上述错误消息,但我一生都无法弄清楚它有什么问题,非常感谢您的帮助。请原谅您可能会看到的任何新手错误。我已经创建了一个球,我正在尝试移动它。
class Ball{
constructor(x,y,xSpeed,ySpeed,r){
this.x =x;
this.y=y;
this.xSpeed=xSpeed;
this.ySpeed=ySpeed;
this.r= r;
}
draw(){
ctx.clearRect(0,0, 500, 200);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.stroke();
}
move()
{
this.x+=this.xSpeed; //error is here
this.y+=this.ySpeed;
if (this.x==0)
{
this.xSpeed=2;
}
else if(this.x==500)
{
this.xSpeed=-2;
}
if (this.y==200)
{
this.ySpeed=-1;
}
else if (this.y==0)
{
this.ySpeed=1;
}
window.requestAnimationFrame(this.move);
}
}
var canvas = document.getElementById("canvas-for-ball");
var ctx = canvas.getContext("2d")
let balls=new Ball (10,10,2,1,5);
balls.draw();
balls.move();
解决方案
问题是,当您调用requestAnimationFrame
并将引用move
作为回调传递给它时,执行回调时this
与您的实例的绑定Ball
会丢失。相反,您必须以仍然绑定到您的实例move
的方式传递。您可以通过使用该方法传递函数引用来做到这一点,该方法接受一个参数,该参数指定回调函数运行时绑定的内容。this
Ball
.bind()
this
class Ball {
constructor(x,y,xSpeed,ySpeed,r){
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.r = r;
}
draw(){
ctx.clearRect(0,0, 500, 200);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.stroke();
}
move(){
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x == 0) {
this.xSpeed = 2;
} else if(this.x == 500) {
this.xSpeed =- 2;
}
if (this.y == 200) {
this.ySpeed =- 1;
} else if (this.y == 0) {
this.ySpeed = 1;
}
window.requestAnimationFrame(this.move.bind(this));
}
}
var canvas = document.getElementById("canvas-for-ball");
var ctx = canvas.getContext("2d")
let balls = new Ball(10,10,2,1,5);
balls.draw();
balls.move();
<canvas id="canvas-for-ball"></canvas>
推荐阅读
- html - CSS Grid:改变一行的方向?子元素是否可以缩进 1/-1 列?
- php - 在 php 表中显示不同的级别
- logging - 你可以在godot中制作一个日志文件吗?
- java - 如何在 Shiro SessionListener 中触发会话到期重定向?
- unit-testing - Azure Devops 是否有与 tcm / import 类似的工具?
- scala - Scala应用无法返回选项
- python - 在 python 中,如何创建一个列表列表,其中每个列表都包含一个开始和结束日期的字符串表示形式?
- java - HttpsURLConnection POST 方法失败。我不知道我是否有正确的编写器和/或输出流编写器。对于多部分/表单数据
- postgresql - NpgSQL 奇怪的行为
- react-native - 如何从 firebase crashlytics 堆栈跟踪文本 index.android.bundle 或 iOS main.jsbundle 获取错误源文件?