HTML and CSS Reference
In-Depth Information
If the source is not passed in, we can simply return the target untouched, as
seen in Listing 7.56.
Listing 7.56 Dealing with only one argument
"test should return target untouched when no source":
function () {
var object = tddjs.extend({});
var properties = [];
for (var prop in object) {
if (tddjs.isOwnProperty(object, prop)) {
properties.push(prop);
}
}
assertEquals(0, properties.length);
}
Now something interesting happens. This test passes in most browsers, even
when source is undefined . This is because of browsers' forgiving nature, but
it is violating ECMAScript 3, which states that a TypeError should be thrown
when a for-in loop is trying to loop null or undefined . Interestingly, Internet
Explorer 6 is one of the browsers that does behave as expected here. ECMAScript
5 changes this behavior to not throw when the object being looped is null or
undefined . Listing 7.57 shows the required fix.
Listing 7.57 Aborting if there is no source
function extend(target, source) {
target = target
||
{};
if (!source) {
return target;
}
/* ... */
}
Note that tddjs.extend always overwrites if target already defines a
given property. We could embellish this method in several ways—adding a boolean
option to allow/prevent overwrite, adding an option to allow/prevent shadowing
of properties on the prototype chain, and so on. Your imagination is your limit.
 
Search WWH ::




Custom Search