我是很新的JS,并通过课程已经在网上了,但很令人沮丧,我只是似乎对我自己这样艰难的时刻,所以我很抱歉,如果这个问题有一个明显的答案。基本上,这个程序在一个盒子里反射一个彩色的球。每次遇到墙壁时,我都希望改变颜色。我想出了一个办法通过把所有的信息在一个功能,但我使用的教程这样做是说(为整洁的代码目的)2层的功能会更好,所以我真的只是想了解如何做我想做的当信息可用于不同的功能时要做,因为我知道我将来必须这样做。我将评论重要的代码行。非常感谢任何能够提供帮助的人。如何使用函数来更改另一个函数的属性?
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 4;
var dy = -4;
var ballRadius = 30;
function drawBall() { \\draws the ball
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#ff0000";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y += dy;
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) { \\says when to bounce
dx = -dx;
drawBall.ctx.fillStyle = "#ff0000"; \\this line and next line are lines I wrote
drawBall.ctx.fill(); \\that are obviously incorrect (same goes for
} \\ if statement below). What am I doing wrong?
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
drawBall.ctx.fillStyle = "#0095DD";
drawBall.ctx.fill();
}
}
setInterval(draw, 10);
遗憾地说,但一个'function'是'object',因为它继承自Object,因此可以做的一切对象可以做。例如'函数A(){的console.log( “A”)}; AB- = “B”; AC =函数(){此();的console.log(this.b + “C” + “A是” +(typeof A))};'然后'Ac()'将输出'Abc A是一个函数'。它可能会支付修正开头的段落。 – Blindman67