为什么注释掉这段代码的alert()行会导致它失败?
我在 javascript 方面遇到了一个非常奇怪的问题。如果您使用以下代码并运行它,它将正常运行,不会出现任何错误,但如果您注释第一个 alert
,它将在第 5 行抛出错误 (var _board = Bomber. BoardFactory.getBoard();
) 说 BoardFactory 不存在(请记住,在第一个警报中,所有内容都运行没有错误)。我已经能够使用 Firefox 和 Chrome 重现这种确切的行为。
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();
});
我的问题是,什么可能导致这种奇怪的行为?警报调用到底是如何让它识别 Bomber.BoardFactory
的呢?
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 = 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();
});
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通过 jslint 运行它,修复了错误(2 个缺少分号和 if 上缺少 {})
现在它似乎可以工作
发生的情况是在定义
Bomber.Game
后您缺少最后一个分号,所以接下来是 (function()....等等,所以它认为你正在调用该函数。如果你在那里有警报,你会被自动分号插入保存。
I ran it through jslint, fixed the errors (2 missing semicolons and missing {} on your if)
Now it seems to work
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.
很难预测哪一个将首先执行:
(function () {
或$(document).ready(function () {
尝试将它们组合起来并声明所有你的功能优先于其他任何事情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