HTML and CSS Reference
In-Depth Information
to outside modification, which could cause the method to return the same id twice,
breaking its contract. By using a closure, we can store the counter in a free variable
that is protected from outside access. Listing 6.20 shows the implementation.
Listing 6.20 Storing state in a free variable
(function () {
var id = 0;
function uid(object) {
if (typeof object.__uid != "number") {
object.__uid = id++;
}
return object.__uid;
}
if (typeof tddjs == "object") {
tddjs.uid = uid;
}
}());
The implementation uses an immediately called anonymous closure to create a
scope in which the id variable can live. The uid function, which has access to this
variable, is exposed to the world as the tddjs.uid method. The typeof check
avoids a reference error if for some reason the file containing the tddjs object has
not loaded.
6.3.2 Iterators
Iterators are objects that encapsulate the enumeration of a collection object. They
provide a consistent API to traverse any kind of collection, and can provide better
control over iteration than what simple for and while loops can, e.g., by ensuring
that an item is never accessed more than once, that items are accessed strictly
sequential and more. Closures can be used to implement iterators rather effortlessly
in JavaScript. Listing 6.21 shows the basic behavior of the iterators created by
tddjs.iterator .
Listing 6.21 Behavior of the tddjs.iterator method
TestCase("IteratorTest", {
"test next should return first item":
function () {
var collection = [1, 2, 3, 4, 5];
 
Search WWH ::




Custom Search