Why does commenting out the alert() line of this code make it fail?
I have a very odd problem with javascript. If you take the following code and run it, it will run fine without any error, but if you comment the first alert
, it will throw an error at line 5 (var _board = Bomber.BoardFactory.getBoard();
) saying BoardFactory doesn't exist (remember that with the first alert everything was running without error). I have been able to reproduce this exact behavior with Firefox and Chrome.
Bomber = {};
Bomber.Game = function () {
var self = {};
var _board = Bom开发者_开发百科ber.BoardFactory.getBoard();
self.init = function () {};
self.start = function () {};
return self;
}
alert("2");
(function () {
var instance;
Bomber.BoardFactory = {};
Bomber.BoardFactory.getBoard = function () {
if (!instance)
instance = new Bomber.Board();
return instance;
};
})();
alert("3");
Bomber.Board = function () {
var self = {};
return self;
}
$(document).ready(function () {
var game = Bomber.Game();
game.init();
game.start();
});
My question, is what can possibly cause this odd behavior ? How on earth is it possible that an alert call makes it recognize the Bomber.BoardFactory
?
I ran it through jslint, fixed the errors (2 missing semicolons and missing {} on your if)
Now it seems to work
Bomber = {};
Bomber.Game = function () {
var self = {};
var _board = Bomber.BoardFactory.getBoard();
self.init = function () {};
self.start = function () {};
return self;
};
//alert("2");
(function () {
var instance;
Bomber.BoardFactory = {};
Bomber.BoardFactory.getBoard = function () {
if (!instance){
instance = new Bomber.Board();
}
return instance;
};
})();
//alert("3");
Bomber.Board = function () {
var self = {};
return self;
};
$(document).ready(function () {
var game = Bomber.Game();
game.init();
game.start();
});
What's happening is you're missing the final semicolon after you define Bomber.Game
, so the next thing is (function()....etc, so it thinks you're calling the function.
If you have the alert there you are saved by automatic semicolon insertion.
it is hard to predict which one will execute first: (function () {
or the $(document).ready(function () {
try to combine those and declare all your functions before anything else
精彩评论