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

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.

主站蜘蛛池模板: 罗山县| 青海省| 东阿县| 万全县| 巫溪县| 娄烦县| 富锦市| 霞浦县| 衢州市| 湖口县| 常熟市| 富锦市| 怀来县| 平定县| 阿尔山市| 扶绥县| 碌曲县| 灯塔市| 卓资县| 石柱| 普陀区| 乌海市| 华阴市| 招远市| 保德县| 蒙自县| 商丘市| 中西区| 萍乡市| 保山市| 抚州市| 个旧市| 鲁甸县| 黎城县| 潍坊市| 镇沅| 临汾市| 遂昌县| 汝阳县| 龙山县| 宾川县|