Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js-未捕获的TypeError:无法读取未定义的at对象(ball)的属性“x”_Javascript_Class_Object - Fatal编程技术网

Javascript js-未捕获的TypeError:无法读取未定义的at对象(ball)的属性“x”

Javascript js-未捕获的TypeError:无法读取未定义的at对象(ball)的属性“x”,javascript,class,object,Javascript,Class,Object,您好,我在尝试运行此代码时收到上面的错误消息,我一辈子都无法找出它的错误,非常感谢您的帮助。请原谅您可能看到的任何新手错误。我已经创建了一个球,我正在尝试移动它 class Ball{ constructor(x,y,xSpeed,ySpeed,r){ this.x =x; this.y=y; this.xSpeed=xSpeed;

您好,我在尝试运行此代码时收到上面的错误消息,我一辈子都无法找出它的错误,非常感谢您的帮助。请原谅您可能看到的任何新手错误。我已经创建了一个球,我正在尝试移动它


        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,即它仍然绑定到球实例。您可以使用h接受一个参数,该参数指定在回调函数运行时此绑定将是什么

班级舞会{ 构造器X,y,X速度,y速度,r{ 这个.x=x; 这个。y=y; this.xSpeed=xSpeed; this.ySpeed=ySpeed; 这个。r=r; } 画{ ctx.clearRect0,0500200; ctx.beginPath; ctx.arcthis.x,this.y,this.r,0,2*Math.PI; ctx.stroke; } 移动{ this.x+=this.xSpeed; this.y+=this.y速度; 如果这个.x==0{ 这个.xSpeed=2; }否则,如果此.x==500{ this.xSpeed=-2; } 如果这个.y==200{ 这个.ySpeed=-1; }否则,如果此.y==0{ 该速度为1; } window.requestAnimationFramethis.move.bindthis; } } var canvas=document.getElementByIdcanvas-for-ball; var ctx=canvas.getContext2d 让球=新球10,10,2,1,5; 球。画; 球。移动;
window.requestAnimationFramethis.move.bindthis;感谢您的回复。这确实消除了错误,但是它实际上并没有使球移动,有什么建议吗?@John您需要再次调用draw,因为移动只会更新坐标。