HTML and CSS Reference
In-Depth Information
7.5.3 Mixins
An object that defines a set of properties that can be used with the
tddjs.extend
method to “bless” other objects is often called a
mixin
. For instance, the Ruby
standard library defines a bunch of useful methods in its
Enumerable
module,
which may be
mixed in
to any object that supports the
each
method. Mixins provide
an incredibly powerful mechanism for sharing behavior between objects. We could
easily port the enumerable module from Ruby to a JavaScript object and mix it in
with, e.g.,
Array.protoype
to give all arrays additional behavior (remember to
not loop arrays with
for-in
). Listing 7.58 shows an example that assumes that the
enumerable
object contains at least a
reject
method.
Listing 7.58
Mixing in the enumerable object to
Array.prototype
TestCase("EnumerableTest", {
"test should add enumerable methods to arrays":
function () {
tddjs.extend(Array.prototype, enumerable);
var even = [1, 2, 3, 4].reject(function (i) {
return i%2==1;
});
assertEquals([2, 4], even);
}
});
Assuming we are in a browser that supports
Array.prototype.forEach
,
we could implement the
reject
method as seen in Listing 7.59.
Listing 7.59
Excerpt of JavaScript implementation of Ruby's enumerable
var enumerable = {
/* ... */
reject: function (callback) {
var result = [];
this.forEach(function (item) {
if (!callback(item)) {
result.push(item);
}
});