官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 胶州市| 阜阳市| 定结县| 武鸣县| 颍上县| 郴州市| 唐山市| 涟源市| 兴海县| 泗阳县| 揭东县| 五常市| 双流县| 张掖市| 岱山县| 桂平市| 谢通门县| 扬中市| 濉溪县| 巴彦淖尔市| 永和县| 涟水县| 原阳县| 神农架林区| 平武县| 象州县| 磐安县| 武川县| 图木舒克市| 寻甸| 兴安盟| 历史| 昆明市| 尤溪县| 东台市| 临猗县| 阜城县| 雷州市| 通州市| 白河县| 日照市|