0

I'm trying to create a simple javascript game and I'm running into a problem accessing a function's data outside of it.

This code works perfectly.

window.onload = function() {
var FPS = 30;
var ground = new myObject();
var twoground = new myObject();
setInterval(function() {
  clear();
  draw();
  ground.draw(0, 325);
  twoground.draw(125,325);
  alert(ground.xval);
}, 1000/FPS);
};

function myObject(){ 
this.draw = function drawground(groundx, groundy){
this.xval=groundx+125;
this.yval = groundy;
var canvas = document.getElementById('canvas')
var  context = canvas.getContext('2d');
var img=new Image()
img.src="ground.png"
img.onload = function() { 
context.drawImage(img,groundx,groundy)}

}

};

The above alerts 125 to the browser every time the interval runs, but that's the only way I can do it, for example if I do the following instead.

window.onload = function() {
var FPS = 30;
var ground = new myObject();
var twoground = new myObject();
setInterval(function() {
  clear();
  draw();
  ground.draw(0, 325);
  twoground.draw(125,325);
  myalert();
}, 1000/FPS);
};

 function myalert()
{
 alert(ground.xval);
}

function myObject(){ 
this.draw = function drawground(groundx, groundy){
this.xval=groundx+125;
this.yval = groundy;
var canvas = document.getElementById('canvas')
var  context = canvas.getContext('2d');
var img=new Image()
img.src="ground.png"
img.onload = function() { 
context.drawImage(img,groundx,groundy)}

}

};

What I would expect is the same thing, as it should be calling myalert, which only displays an alert, in the same interval, but it doesn't. I feel like I'm missing something with the way javascript functions work.

4

2 回答 2

0

当您使用关键字在函数内声明变量时var,该变量将放在函数的本地范围内。要使其在函数外部可访问,您可以通过省略var关键字将其置于全局范围内。

但是,您可能还需要考虑重构代码以避免全局变量,方法是使它们成为自定义对象的属性,或者将它们作为函数参数传递。

于 2013-05-06T18:27:58.367 回答
0

JavaScript 是静态作用域的,而不是动态作用域的。当您ground在第二个示例中引用时,您指的是名称为 的全局变量ground,而不是第一个示例中的局部变量ground。传递给的函数从其父函数中setInterval()捕获局部变量,并且在评估ground时它仍在范围内。alert()

于 2013-05-06T18:28:11.503 回答