- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 422字
- 2021-07-09 19:07:37
The namespace pattern
Excessive use of the global scope is almost a taboo in JavaScript. When you build larger programs, it is sometimes difficult to control how much the global scope is polluted. Namespace can reduce the number of globals created by the program and also helps in avoiding naming collisions or excessive name prefixing. The idea of using namespaces is creating a global object for your application or library and adding all these objects and functions to that object rather than polluting the global scope with objects. JavaScript doesn't have an explicit syntax for namespaces, but namespaces can be easily created. Let's consider the following example:
function Car() {} function BMW() {} var engines = 1; var features = { seats: 6, airbags:6 };
We are creating all this in the global scope. This is an anti-pattern, and this is never a good idea. We can, however, refactor this code and create a single global object and make all the functions and objects part of this global object as follows:
// Single global object var CARFACTORY = CARFACTORY || {}; CARFACTORY.Car = function () {}; CARFACTORY.BMW = function () {}; CARFACTORY.engines = 1; CARFACTORY.features = { seats: 6, airbags:6 };
By convention, the global namespace object name is generally written in all caps. This pattern adds namespace to the application and prevents naming collisions in your code and between your code and external library that you use. Many projects use a distinct name after their company or project to create a unique name for their namespace.
Though this seems like an ideal way to restrict your globals and add a namespace to your code, it is a bit verbose; you need to prefix every variable and function with the namespace. You need to type more and the code becomes unnecessarily verbose. Additionally, a single global instance would mean that any part of the code can modify the global instance and the rest of the functionality gets the updated state—this can cause very nasty side-effects. A curious thing to observe in the earlier example is this line—var CARFACTORY = CARFACTORY || {};
. When you are working on a large code base, you can't assume that you are creating this namespace (or assigning a property to it) for the first time. It is possible that the namespace may pre-exist. To make sure that you create the namespace only if it is not already created, it is safe to always rely on the quick defaulting via a short-circuit ||
operator.
- Python程序設計教程(第2版)
- C語言程序設計實踐教程(第2版)
- UML和模式應用(原書第3版)
- Visual FoxPro程序設計教程
- Git高手之路
- 面向對象程序設計(Java版)
- MySQL數據庫基礎實例教程(微課版)
- Visual FoxPro程序設計習題集及實驗指導(第四版)
- Windows Phone 8 Game Development
- UX Design for Mobile
- Web前端開發技術:HTML、CSS、JavaScript
- Implementing Microsoft Dynamics NAV(Third Edition)
- 從“1”開始3D編程
- LabVIEW數據采集(第2版)
- Java EE 程序設計