我很难理解“立即调用的函数表达式”( lot )。
我正在设计一个游戏(我现在有一个工作模型,但它不是面向对象的,我的目标是更好地设计和实现代码),我被告知不要让我的对象引用成为全局引用。
我现在的情况是这样的。
var engine = new _engine();
engine.count++; //there's a lot more to the engine, I just haven't converted it yet以下是我尝试过的:
(function() { var engine = new _engine(); }());
engine.count++; //error, engine is not defined所以,现在我正在尝试这个,它是有效的,但我害怕它可能仍然是全球性的!
var engine = (function(){ return new _engine(); }());
engine.count++; //works, but is this still global?JavaScript中的对象设计对我来说是一个非常新的概念,所以我想确保我学习到了正确的方法,同时也理解了为什么这样做是可行的。
请注意,我需要能够访问引擎从任何地方的网页。这是否意味着有必要建立一个全球性的体系?为什么全球都会如此皱眉?(其他对象基于函数返回和布尔变量引用引擎)
发布于 2013-11-22 18:57:21
这里有一个你想要达到的可接受设计的例子。最后,应用程序将有一个入口点,并使用一个全局变量,该变量用作应用程序的命名空间。
您可以而且很可能应该在构造时使用依赖项注入(或者使用注入器)将依赖项注入到对象中,而不是依赖于外部众所周知的变量。
如果您真的很认真地编写模块化代码,那么请看一下RequireJS.
Engine.js
(function (ns) {
function Engine() {
}
Engine.prototype.someMethod = function () {
};
ns.Engine = Engine;
})(window.myNamespace = window.myNamespace || {});Game.js
(function (ns) {
function Game(engine) {
this._engine = engine;
}
Game.prototype.start = function () {
this._engine.someMethod();
};
ns.Game = Game;
})(window.myNamespace = window.myNamespace || {});app.js
//kickstart your app
(function () {
var engine = new myNamespace.Engine(),
//init the Game while injecting the engine dependency
game = new myNamespace.Game(engine);
game.start();
})();发布于 2013-11-22 17:49:32
我想你要找的是:
(function() {
var engine = new _engine();
engine.count++;
// all other code depending on engine should be in here as well
})();您的代码将执行与原始版本完全相同的操作,但是现在engine是本地的,而不是全局的。
编辑:在评论中讨论之后,听起来确实需要engine才是全局的。在这种情况下,您可能可以保持代码的原样,但是为了确保您没有将任何其他变量公开为engine之外的全局变量,您可以执行以下操作:
var engine = (function() {
var engine = new _engine();
engine.count++;
// any other code from your engine file (probably the _engine definition, etc)
return engine; // return local engine from the IIFE
})();或者(这是jQuery和其他一些流行库所使用的):
(function(window) {
var engine = new _engine();
engine.count++;
// any other code from your engine file (probably the _engine definition, etc)
window.engine = engine; // assign engine to window.engine to make it global
})(window);https://stackoverflow.com/questions/20151246
复制相似问题