Advice on Javascript variable initialization
This question already has an answer here:
Unless you are aware that you are creating a global variable (which is mostly considered bad practice, anyway), it's not ok.
If you came from a language like Java, it's natural to do something like:
int foo = bar = 0;
Both variables foo and bar will be initialized with value 0, both inside the current scope. But in Javascript:
var foo = bar = 0;
Will create the variable foo inside the current scope and a global variable bar.
The problem
I was debugging on a game I'm writing for about an hour, before understanding my mistake. I had a code like:
function Player() {
var posX = posY = 0;
}
function Bullet() {
var posX = posY = 0;
}
var player = new Player;
var bullet = new Bullet;
Variable posY is global. Any method on one object that changes the value of posY will also change it for the other object.
What happened: every time a bullet object moved through the screen vertically (changing what it should be it's own posY), the player object would be teleported to bullet's Y coordinate.
Solved by simply separating the variable declaration to:
var posX = 0;
var posY = 0;
链接地址: http://www.djcxy.com/p/69976.html
下一篇: 关于Javascript变量初始化的建议