html - How to call class function in JavaScript? - Stack Overflow

New to JavaScript so might be something simple.Getting an Error:ball.html:46 Uncaught SyntaxError: Unex

New to JavaScript so might be something simple.

Getting an Error:

ball.html:46 Uncaught SyntaxError: Unexpected identifier

Why this is happening? I am new to JavaScript. But I tried everything in my knowledge to fix it. Tried removing the function but then it gives error:

draw() function is not defined in repeatMe() function.

HTML and JavaScript:

<!DOCTYPE html>

<html>

  <head>
    <meta charset="UTF-8">
    <title>Canvas</title>

    <style type="text/css">
      body {
          background-color: white;
      }

      canvas { 
        border: 3px solid black; 
    }
    </style>

  </head>

  <body>

    <canvas id="canvas-for-ball" height="800px" width="800px"></canvas>

    <script type="text/javascript">
      // Gets a handle to the element with id canvasOne.
      var canvas = document.getElementById("canvas-for-ball");
      // Get a 2D context for the canvas.
      var ctx = canvas.getContext("2d");

      // The vertical location of the ball.
      var y = 10;
      var x = 10;
      var ballRadius = 3;
      var ySpeed = 1;

      class Ball {
        constructor(x, y, ballRadius, ySpeed) {
            this.x = x;
            this.y = y
            this.ballRadius = BallRadius;
            this.ySpeed = ySpeed;
        }//endConstructor

        function drawball() {
            ctx.beginPath();
            ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
            ctx.stroke();
        }//endDrawball

        function draw() {
            ctx.clearRect(1, 1, 800, 800);
            drawball(); 
        }//endDraw

        function move() {
            // Update the y location.
            y += ySpeed;
            console.log(y);
        }
      } //endBall


      // A function to repeat every time the animation loops.
      function repeatme() {
        // Draw the ball (stroked, not filled).
        draw();
        move();

        //catch ball at bottom
        if (y == 800)
        {
             ySpeed = 0;
        }

        window.requestAnimationFrame(repeatme);
      }

      // Get the animation going.
      repeatme();
    </script>

  </body>

</html>

New to JavaScript so might be something simple.

Getting an Error:

ball.html:46 Uncaught SyntaxError: Unexpected identifier

Why this is happening? I am new to JavaScript. But I tried everything in my knowledge to fix it. Tried removing the function but then it gives error:

draw() function is not defined in repeatMe() function.

HTML and JavaScript:

<!DOCTYPE html>

<html>

  <head>
    <meta charset="UTF-8">
    <title>Canvas</title>

    <style type="text/css">
      body {
          background-color: white;
      }

      canvas { 
        border: 3px solid black; 
    }
    </style>

  </head>

  <body>

    <canvas id="canvas-for-ball" height="800px" width="800px"></canvas>

    <script type="text/javascript">
      // Gets a handle to the element with id canvasOne.
      var canvas = document.getElementById("canvas-for-ball");
      // Get a 2D context for the canvas.
      var ctx = canvas.getContext("2d");

      // The vertical location of the ball.
      var y = 10;
      var x = 10;
      var ballRadius = 3;
      var ySpeed = 1;

      class Ball {
        constructor(x, y, ballRadius, ySpeed) {
            this.x = x;
            this.y = y
            this.ballRadius = BallRadius;
            this.ySpeed = ySpeed;
        }//endConstructor

        function drawball() {
            ctx.beginPath();
            ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
            ctx.stroke();
        }//endDrawball

        function draw() {
            ctx.clearRect(1, 1, 800, 800);
            drawball(); 
        }//endDraw

        function move() {
            // Update the y location.
            y += ySpeed;
            console.log(y);
        }
      } //endBall


      // A function to repeat every time the animation loops.
      function repeatme() {
        // Draw the ball (stroked, not filled).
        draw();
        move();

        //catch ball at bottom
        if (y == 800)
        {
             ySpeed = 0;
        }

        window.requestAnimationFrame(repeatme);
      }

      // Get the animation going.
      repeatme();
    </script>

  </body>

</html>
Share Improve this question edited Oct 19, 2018 at 22:00 Vikram Deshmukh 15.8k4 gold badges38 silver badges41 bronze badges asked Oct 19, 2018 at 21:17 TomajuliTomajuli 271 gold badge1 silver badge5 bronze badges 1
  • 2 Functions defined in a class don't need the function prefix. function drawball() should just be drawball() You are confusing a few concepts here so I will throw together a quick example for you. – Adam H Commented Oct 19, 2018 at 21:27
Add a ment  | 

4 Answers 4

Reset to default 2

You need to see this before jumping into using JavaScript.Classes in JavaScript and few basics of programing in OOPS.

The issue you are facing is calling a function which doesn't exist. Also you have created class wrongly, this is not how functions are created in class in JavaScript. Also you can't access class function directly, that's why they are in class. Need to create object of that class and that object will be used to call class function.

Change to this:

class Ball {
    constructor(x, y, ballRadius, ySpeed) {
        this.x = x;
        this.y = y
        this.ballRadius = BallRadius;
        this.ySpeed = ySpeed;
    }//endConstructor

    drawball() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
        ctx.stroke();
    }//endDrawball

    draw() {
        ctx.clearRect(1, 1, 800, 800);
        drawball(); 
    }//endDraw

    move() {
        // Update the y location.
        y += ySpeed;
        console.log(y);
    }
  } //endBall

  let Ball = new Ball(x, y, ballRadius, ySpeed);
  // Note this is constructor calling so pass value for these arguments here

// A function to repeat every time the animation loops.
function repeatme() {

    // Draw the ball (stroked, not filled).
    Ball.draw();
    Ball.move();

    //catch ball at bottom
    if (Ball.y == 800)
    {
         Ball.ySpeed = 0;
    }

    window.requestAnimationFrame(repeatme);
} 

Would highly remend to read few docs before jumping into JavaScript, as it's get confusing with callsbacks, promises, closures, hoisting and many more.

There is a problem here in that you're attempting to invoke some functions which don't exist:

  function repeatme() {
    // Draw the ball (stroked, not filled).
    draw(); //<-- Where is this function?
    move(); //<-- Where is this function?

    //catch ball at bottom
    if (y == 800)
    {
         ySpeed = 0;
    }

    window.requestAnimationFrame(repeatme);
  }

I presume you want to use the functions which are part of the ball class. If so, you need to spin off a new instance of a Ball, and access the functions from there...:

  function repeatme() {
    // Draw the ball (stroked, not filled).
    let ball = new Ball(x, y, ballRadius, ySpeed); //<--- create a new ball instance
    ball.draw(); //<-- invoke the function which resides on a ball
    ball.move(); //<-- invoke the function which resides on a ball

    //catch ball at bottom
    if (y == 800)
    {
         ySpeed = 0;
    }

    window.requestAnimationFrame(repeatme);
  }

That "might" fix your code, but there is also a lot of other concepts happening here that you need to research. For example, you have some variables scoped OUTSIDE the context of a Ball, yet inside your Ball class, you are referencing them. Thus, you've essentially created a closure here... probably by accident.

You ought to just let the Ball do it's thing, without all these scoped variables... sort've like so:

// Gets a handle to the element with id canvasOne.
      var canvas = document.getElementById("canvas-for-ball");
      // Get a 2D context for the canvas.
      var ctx = canvas.getContext("2d");

//< -- Notice I removes these vars here, since we really just want to feed those into the constructor of a Ball...

      class Ball {
        constructor(x, y, ballRadius, ySpeed) {
            this.x = x;
            this.y = y
            this.ballRadius = ballRadius;
            this.ySpeed = ySpeed;
        }//endConstructor

        drawball() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.ballRadius, 0, 2 * Math.PI);
            ctx.stroke();
        }//endDrawball

        draw() {
            ctx.clearRect(1, 1, 800, 800);
            this.drawball(); 
        }//endDraw

        move() {
            // Update the y location.
            this.y += this.ySpeed;
            console.log(this.y);
        }
      } //endBall


      // A function to repeat every time the animation loops.
      function repeatme() {
        // Draw the ball (stroked, not filled).
         // The vertical location of the ball.  Remember the variables above?  Now the values are fed into here instead...
        let ball = new Ball(10, 10, 3, 1)
        ball.draw();
        ball.move();

        //catch ball at bottom
        if (ball.y == 800)
        {
             ball.ySpeed = 0;
        }

        window.requestAnimationFrame(repeatme);
      }

      // Get the animation going.
      repeatme();

I just defined below functions out of class()

function drawball() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
        ctx.stroke();
    }//endDrawball

    function draw() {
        ctx.clearRect(1, 1, 800, 800);
        drawball(); 
    }//endDraw

    function move() {
        // Update the y location.
        y += ySpeed;
        console.log(y);
    }

Updated working code:

<!DOCTYPE html>

<html>

  <head>
    <meta charset="UTF-8">
    <title>Canvas</title>

    <style type="text/css">
      body {
          background-color: white;
      }

      canvas { 
        border: 3px solid black; 
    }
    </style>

  </head>

  <body>

    <canvas id="canvas-for-ball" height="800px" width="800px"></canvas>

    <script type="text/javascript">
      // Gets a handle to the element with id canvasOne.
      var canvas = document.getElementById("canvas-for-ball");
      // Get a 2D context for the canvas.
      var ctx = canvas.getContext("2d");

      // The vertical location of the ball.
      var y = 10;
      var x = 10;
      var ballRadius = 3;
      var ySpeed = 1;

      class Ball {
        constructor(x, y, ballRadius, ySpeed) {
            this.x = x;
            this.y = y
            this.ballRadius = BallRadius;
            this.ySpeed = ySpeed;
        }//endConstructor

      } //endBall

        function drawball() {
            ctx.beginPath();
            ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
            ctx.stroke();
        }//endDrawball

        function draw() {
            ctx.clearRect(1, 1, 800, 800);
            drawball(); 
        }//endDraw

        function move() {
            // Update the y location.
            y += ySpeed;
            console.log(y);
        }
      // A function to repeat every time the animation loops.
      function repeatme() {
        // Draw the ball (stroked, not filled).
        draw();
        move();

        //catch ball at bottom
        if (y == 800)
        {
             ySpeed = 0;
        }

        window.requestAnimationFrame(repeatme);
      }

      // Get the animation going.
      repeatme();
    </script>

  </body>

</html>

The root of the issue is that you are creating a class but then never creating an instance of that class to call your functions on. Here is a cleaned up functioning example with ments explaining what things are doing differently.

// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");

// The vertical location of the ball.
var y = 10;
var x = 10;
var ballRadius = 3;
var ySpeed = 1;

class Ball {
  constructor(x, y, ballRadius, ySpeed) {
    // changed these to set the private members
    this._x = x;
    this._y = y
    // updated the assignment here, it had the wrong case
    this._ballRadius = ballRadius;
    this._ySpeed = ySpeed;
  } //endConstructor
  
  // added a setter for ySpeed so you can acess it outside of the class
  set VerticleSpeed(val){
    this._ySpeed = val;
  }
  
  // added a getter/setter for y so you can access it outside of the class
  get VerticlePosition(){
    return this._y;
  }
  
  // remove the function keyword, it's not needed
  drawball() {
    ctx.beginPath();
    // updated this to reference the properties on the class
    ctx.arc(this._x, this._y, this._ballRadius, 0, 2 * Math.PI);
    ctx.stroke();
  } //endDrawball

  // remove the function keyword, it's not needed
  draw() {
    ctx.clearRect(1, 1, 800, 800);
    this.drawball();
  } //endDraw

  // remove the function keyword, it's not needed
  move() {
    // Update the y location.
    // updated this to reference the properties on the class
    this._y += this._ySpeed;
    console.log("Ball position", this._y);
  }
} //endBall


// A function to repeat every time the animation loops.
function repeatme() {
  // Draw the ball (stroked, not filled).
  // upated to call the functions on the instance of the class
  myBall.draw();
  myBall.move();

  //catch ball at bottom
  // changed to check the property on the instance of the class
  // changed this bit to make it bounce and if its outside the bounds, this is just me showing off and having fun with this example
  
  if (myBall.VerticlePosition >= canvas.height) {
    // changed to assign the property on the instance of the class
    myBall.VerticleSpeed = -ySpeed;
  } else if (myBall.VerticlePosition <= 0){
    myBall.VerticleSpeed = ySpeed;
  }

  window.requestAnimationFrame(repeatme);
}

// create an instance of your class
let myBall = new Ball(x, y, ballRadius, ySpeed)
// Get the animation going.
repeatme();
body {
  background-color: white;
}

canvas {
  border: 3px solid black;
}

.as-console-wrapper {
  max-height: 25px !important;
}
<!DOCTYPE html>

<html>

<head>
  <meta charset="UTF-8">
  <title>Canvas</title>
</head>

<body>

  <canvas id="canvas-for-ball" height="150px" width="400px"></canvas>

</body>

</html>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744179329a4561906.html

相关推荐

  • html - How to call class function in JavaScript? - Stack Overflow

    New to JavaScript so might be something simple.Getting an Error:ball.html:46 Uncaught SyntaxError: Unex

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信