JavaScript 新手,所以可能很简单。
出现错误:
ball.html:46 Uncaught SyntaxError: Unexpected identifier
为什么会发生这种情况?我是 JavaScript 新手。但我尽了我所知的一切来解决它。尝试删除 function
但随后出现错误:
draw() function is not defined in repeatMe() function.
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 之前,您需要先了解这一点。 Classes in 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 混淆。 , promises , closures , hoisting还有很多。
关于javascript - JavaScript中如何调用类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52900036/