HTML and CSS Reference
In-Depth Information
implicit binding. Because importing namespaces effectively caches the object inside
the closure, it can also cause trouble when trying to mock or stub the imported
Using namespaces is a highly useful way to organize code in a clean way without
tripping up the global namespace. You might worry that the property lookups
come with a performance penalty, which they do, but compared with, e.g., DOM
manipulation, the impact of these namespaces will be minute.
6.3 Stateful Functions
A closure can maintain state through its free variables. The scope chain that allows
access to these free variables is only accessible from within the scope chain itself,
which means that free variables by definition are private. In Chapter 7, Objects and
Prototypal Inheritance, we will see how this can be used to create objects with private
state, a feature not otherwise offered by JavaScript (i.e., no private keyword), in
a pattern popularized as “the module pattern.”
In this section we will use closures to hide implementation details for functions.
6.3.1 Generating Unique Ids
The ability to generate unique ids for any given object is useful whenever we want
to use objects and functions as, e.g., property keys in objects. As we'll see in the
next chapter, property identifiers in JavaScript are always coerced to strings; so even
though we can set a property whose key is an object, it won't do what we expect.
Another useful application of unique ids in the case of DOM elements. Storing
data as properties of DOM elements can cause memory leaks and other undesired
behavior. One way to avoid these problems, currently employed by most major
libraries, is to generate a unique id for an element, and keep an element storage
separate from the element. This allows for an API that can get and set data on the
element without actually storing data other than the unique id directly on it.
As an example of a stateful closure, we will implement a tddjs.uid method.
The method accepts an object and returns a numeric id, which is stored in a property
on the object. Listing 6.19 shows a few test cases describing its behavior.
Listing 6.19 Specification of the uid function
TestCase("UidTest", {
"test should return numeric id":
function () {
var id = tddjs.uid({});
Search WWH ::

Custom Search