簡體   English   中英

如何在JavaScript中調用類函數?

[英]How to call class function in JavaScript?

JavaScript的新手,可能很簡單。

出現錯誤:

ball.html:46未捕獲的SyntaxError:意外的標識符

為什么會這樣呢? 我是JavaScript新手。 但是我盡力修復了所有問題。 嘗試刪除該function但隨后出現錯誤:

在repeatMe()函數中未定義draw()函數。

HTML和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>

您需要先了解這一點,然后再開始使用JavaScript。 JavaScript中的類以及OOPS中的一些編程基礎知識。

您面臨的問題是調用一個不存在的函數。 另外,您錯誤地創建了類,這不是在JavaScript中的類中創建函數的方式。 另外,您不能直接訪問類函數,這就是它們在類中的原因。 需要創建該類的對象,並且該對象將用於調用類函數。

更改為此:

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);
} 

強烈推薦跳進的JavaScript之前先閱讀一些文檔,因為這是獲得與混亂callsbacks承諾關閉懸掛等等。

這里存在一個問題,您正在嘗試調用一些不存在的函數:

  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);
  }

我想您想使用屬於球類的功能。 如果是這樣,您需要衍生一個Ball的新實例,並從那里訪問函數...:

  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);
  }

這種“可能”會修復您的代碼,但是這里還需要研究許多其他概念。 例如,您有一些變量的作用域超出Ball的范圍,但是在Ball類內部,您正在引用它們。 因此,您實際上是在這里創建了一個閉合……可能是偶然的。

您應該只讓Ball來完成它,而不需要所有這些范圍變量...就像這樣:

// 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();

我只是在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);
    }

更新的工作代碼:

<!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>

問題的根源在於您正在創建一個類,但從未創建該類的實例來調用您的函數。 這是一個清理后的功能示例,帶有注釋,解釋了事情的不同之處。

 // 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM