只是捎带到其他答案建议是什么,这种技术是最常用的(在浏览器的研究与开发)当你“命名空间”一些JS代码。 Namespacing非常有用,因为它可以帮助开发人员通过在window
下的一个名称空间下添加所有代码来减少全局变量污染。
这也有助于开发人员modularise的代码。
这里是你可能会不时看到时间window
下添加代码到一个单一命名空间的模式。
// This first function is what's known as an Immediately-invoked
// function expression (IIFE). `window` is passed in as an argument
// to the function - all other declared variables are local to the scope
// of the function so you don't get anything leaking to global.
// PS, the semi-colon is there before the opening parenthesis to prevent
// any errors appearing if you minimise your code
;(function (window) {
// Here we declare something new to add to the namespace
// It could be another object, a string, an array, or a constructor
// like Model
function Model() {...}
// If namespace `window.app` doesn't exist instantiate it with
// an empty object. If it _does_ exist it probably means that another
// module like this one has already been added to the namespace.
window.app = window.app || {};
// Then assign your new module as a property under that namespace
window.app.Model = Model;
})(window);
然后,您可以使用它以后是这样的:
var model = new app.Model();
var game = new Game(model);
对于进一步阅读:Addy Osmani on namespacing。
的可能的复制[JavaScript和示例模块模式](https://stackoverflow.com/questions/17776940/javascript-module-pattern-with-example) – yuriy636