- 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.
- Puppet 4 Essentials(Second Edition)
- DB2 V9權威指南
- 大學計算機應用基礎實踐教程
- Apache Spark 2.x Machine Learning Cookbook
- 網(wǎng)頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- 64位匯編語言的編程藝術
- Interactive Applications Using Matplotlib
- FFmpeg入門詳解:音視頻原理及應用
- The Complete Coding Interview Guide in Java
- Learning OpenStack Networking(Neutron)
- Oracle 18c 必須掌握的新特性:管理與實戰(zhàn)
- Java面向對象程序設計
- 寫給程序員的Python教程
- Koa與Node.js開發(fā)實戰(zhàn)
- Visual C#(學習筆記)