gpt4 book ai didi

javascript - 声明后立即 undefined variable ?

转载 作者:行者123 更新时间:2023-11-28 05:23:08 24 4
gpt4 key购买 nike

我正在使用 var/function 类在 javascript 中创建一个游戏循环(需要一个更好的词)。但是,我有一个奇怪的错误,其中 javascript 声明变量在声明后立即未定义...

main.js:39 Uncaught ReferenceError: game is not defined

在这种情况下,那一行是;

game.context.beginPath();

但是,直到 init 函数调用 game.balls.push(/../) 时才会调用此行;难道我此时还没有宣布“游戏”,还是我遗漏了什么?

这是我的代码(抱歉太长了,希望其中的大部分内容可以被忽略):

/*
Keep This: #217398
*/

var Game = function () {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');

this.balls = [];

var that = this;

this.start = function () {
requestAnimationFrame(that.update);
};
this.update = function () {
that.draw();
requestAnimationFrame(that.update);
};
this.draw = function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

for(var x = 0; x < this.balls.length; x++){
this.balls[x].draw();
}
};

this.start();
};

var Ball = function (x, y) {
this.x = x;
this.y = y;
this.dx = 2;
this.dy = 2;
this.ballRadius = 10;

this.draw = function(){
game.context.beginPath();
game.context.arc(this.x, this.y, this.ballRadius, 0, Math.PI*2);
game.context.fillStyle = 'black';
game.context.fill();
game.context.closePath();

this.x += this.dx;
this.y += this.dy;

if(this.x + this.dx > game.canvas.width - this.ballRadius || this.x + this.dx < this.ballRadius)
this.dx = -this.dx;
if(this.y + this.dy > game.canvas.height - this.ballRadius || this.y + this.dy < this.ballRadius)
this.dy = -this.dy;
};
};

function init(){
var game = new Game();

game.canvas.addEventListener('click', function(){
game.balls.push(new Ball(100, 100));
});
}

最佳答案

更新 Ball() 以便您可以显式传递对 Game() 实例的引用:

var Ball = function (game, x, y) {
this.x = x;
this.y = y;

// etc
};

然后:

function init(){
var game = new Game();

game.canvas.addEventListener('click', function(){
game.balls.push(new Ball(game, 100, 100));
});
}

现在 Ball() 代码可以访问对您创建的 Game() 实例的引用。

关于javascript - 声明后立即 undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35894962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com