HTML and CSS Reference
In-Depth Information
function () {
var existing = {};
tddjs.nstest = { nested: { existing: existing } };
var result = tddjs.namespace("nstest.nested.ui");
assertSame(existing, tddjs.nstest.nested.existing);
assertObject(tddjs.nstest.nested.ui);
}
});
namespace
is expected to be implemented as a method on the global
tddjs
object, and manages namespaces inside it. This way
tddjs
is completely sandboxed
inside its own namespace, and using it along with immediately called closures will
ensure we don't leak properties to the global object. Its implementation is found
in Listing 6.16. Save it in a file called
tdd.js
; we will add more utilities to this
file/namespace throughout the topic.
Listing 6.16
The
namespace
function
var tddjs = (function () {
function namespace(string) {
var object = this;
var levels = string.split(".");
for(vari=0,l=levels.length; i < l; i++) {
if (typeof object[levels[i]] == "undefined") {
object[levels[i]] = {};
}
object = object[levels[i]];
}
return object;
}
return {
namespace: namespace
};
}());
This implementation shows a few interesting uses of functions. It wraps the
entire implementation in a closure, returning an object literal that is assigned to the
global
tddjs
object.
Avoiding the trouble with named function expressions and taking advantage
of the fact that the closure creates a local scope, we define
namespace
using a