HTML and CSS Reference
In-Depth Information
accept an optional properties argument. We will discuss this method further in
Chapter 8, ECMAScript 5th Edition.
7.5.2 The tddjs.extend Method
Often we want to borrow behavior from one or more other objects to build the
functionality we're after. We've seen this a couple of times already. Remember the
arguments object? It acts roughly like an array, but it is not a true array, and
as such, lacks certain properties we might be interested in. The arguments ob-
ject does, however, possess the most important aspects of an array: the length
property, and numerical indexes as property names. These two aspects are enough
for most methods on Array.prototype to consider arguments an object
that “walks like a duck, swims like a duck, and quacks like a duck” and there-
fore is a duck (or rather, an array). This means that we can borrow methods from
Array.prototype by calling them with arguments as this , as seen in
Listing 7.50.
Listing 7.50 Borrowing from Array.prototype
"test arguments should borrow from Array.prototype":
function () {
function addToArray() {
var args = Array.prototype.slice.call(arguments);
var arr = args.shift();
return arr.concat(args);
}
var result = addToArray([], 1, 2, 3);
assertEquals([1, 2, 3], result);
}
The example borrows the slice function and calls it on the arguments
object. Because we don't give it any other arguments, it will return the whole array,
but the trick is now we've effectively converted arguments to an array, on which
we can call the usual array methods.
Remember in Chapter 5, Functions, we illustrated implicit binding of this
by copying a function from one object to another. Doing so causes both objects
to share the same function object, so it's a memory efficient way to share behavior.
Listing 7.51 shows an example.
 
Search WWH ::




Custom Search