gpt4 book ai didi

javascript - 一个变量没有定义,但我之前初始化了它

转载 作者:行者123 更新时间:2023-11-30 13:02:55 25 4
gpt4 key购买 nike

我用 nodejs 和 javascript 写了一个客户端。当我调试代码时,控制台说坐标的 X1 变量没有定义,但我之前已经初始化了它。谁能为我解释一下?

变量位于“localPlayer = new Player(X1, Y1);” var canvas = document.getElementById("绘画");

  var socket;     //Socket connection

var localPlayer, remotePlayers; // local and remote players
var context2D = canvas.getContext("2d");

var lifecount = 3; // frogger has three life values
var score = 0; // when frogger accross a line successfully it will get 10 points

//initialized the coordinates
function initcoordinates(){

var pipe0X=0,pipe0Y=110;
var spider1X= 0,spider1Y=140;
var spider2X= 0,spider2Y=230;
var X1=300,Y1=450; // frogger's ordinary coordinate
var pipe1X=0,pipe1Y=170;
var pipe2X= 0,pipe2Y=200;
var rocketX = 0,rocketY=300;
var carX = 0, carY =330;
var wheelX= 0,wheelY=360;
var car1X= 0, car1Y=390;
var car2X= 0, car2Y=420;
};

function initimage(){

var picpipe0 = new Image();
var pic1=new Image();
var picpipe1 = new Image(); // pipe image
var picpipe2 = new Image();
var spider1 = new Image();
var spider2 = new Image();
var gresp1 = new Image();
var gresp2 = new Image();
var rocket = new Image();
var car = new Image();
var wheel = new Image();
var car1 = new Image();
var car2 = new Image();



//load image
picpipe0.src = "pipe.jpg";
pic1.src = "qingwa.jpg";
picpipe1.src = "pipe.jpg";
picpipe2.src = "pipe.jpg";
spider1.src="spider.jpg";
spider2.src="spider.jpg";
gresp1.src = "gresp.jpg";
gresp2.src = "gresp.jpg";

rocket.src = "rocket.jpg";
car.src = "car.jpg";
wheel.src = "wheel.jpg";
car1.src = "car1.jpg";
car2.src = "car2.jpg";

};
/**************************************************
** GAME INITIALISATION
**************************************************/
function init(){

initcoordinates();
initimage();

// Initialise socket connection
socket = io.connect("http://localhost", {port: 8000, transports: ["websocket"]});



// Initialise remote players array
remotePlayers = [];

// Initialise the local player
localPlayer = new Player(X1, Y1);



// Start listening for events
setEventHandlers();



}

最佳答案

您的 X1 变量在 initcoordinates 函数中是局部范围的,它不能被 init 函数访问。不仅 X1 变量是本地变量,而且您在 initcoordinates 函数中设置的所有坐标都只会在该函数内部可见。我建议您在外部声明这些变量,在围绕其他变量的直接函数中,如下所示:

(function(){
var X1;

function initcoordinates(){
X1 = ...
}

function init(){
//do something with the X1 variable here...
}

})();

这样,您的所有函数将共享对在您的直接函数范围内声明的变量的访问权限。

关于javascript - 一个变量没有定义,但我之前初始化了它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727203/

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