一个variables没有被定义,但我已经初始化它之前

我写了一个客户端nodejs和javascript.when我debugging代码的控制台说,X1的坐标variables没有定义,但我初始化它,谁可以解释给我?

variables位于“localPlayer =新玩家(X1,Y1);” var canvas = document.getElementById(“painting”);

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

你的X1variables本地在initcoordinates函数中,它不能被init函数访问。 不仅X1variables是局部的,而且你在initcoordinates函数中设置的所有坐标只会在这个函数中可见。 我build议你在外面声明这些variables,在其他函数周围的一个直接函数中,像这样:

 (function(){ var X1; function initcoordinates(){ X1 = ... } function init(){ //do something with the X1 variable here... } })(); 

这样,所有的函数将共享对你的直接函数范围内声明的variables的访问。