HTML and CSS Reference
In-Depth Information
function declaration and then assign it to the namespace property of the returned
The namespace function starts resolving namespaces from this . Doing so
allows the function to be easily borrowed to create namespaces in other objects
than tddjs . Listing 6.17 shows an example of borrowing the method to create
namespaces inside another object.
Listing 6.17 Creating custom namespaces
"test namespacing inside other objects":
function () {
var custom = { namespace: tddjs.namespace };
As the test shows, the tddjs object is not modified when calling the method
through another object, which should not be surprising. Importing Namespaces
When organizing code in namespaces, we might tire from all the typing. Program-
mers are lazy creatures, and typing tddjs.ajax.request might be too much
to ask. As we already saw, JavaScript does not have native namespaces, and so there
is no import keyword to import a set of objects into the local scope. Luckily,
closures have local scope, which means that we can simply assign nested objects to
local variables to “import” them. Listing 6.18 shows an example.
Listing 6.18 Using a local variable to “import” a namespace
(function () {
var request = tddjs.ajax.request;
request(/* ... */);
/* ... */
Another advantage of this technique is that, unlike with global variables, local
variable identifiers can safely be minified. Thus, using local aliases can help reduce
the size of scripts in production as well.
Be careful when making local aliases to methods as in the above example. If the
method is dependent on its this object, such local importing effectively breaks
Search WWH ::

Custom Search