HTML and CSS Reference
In-Depth Information
// Object.prototype
assertFalse(object1.toString === chris.toString);
// Deleting the custom property unshadows the
// inherited Object.prototype.toString
delete chris.toString;
assertEquals(object1.toString, chris.toString);
}
});
As seen in Listing 7.3, object1 and object2 don't define a toString
property and so they share the same object—the Object.prototype.
toString method—via the prototype chain. The chris object, on the other
hand, defines its own method, shadowing the toString property on the
prototype chain. If we delete the custom toString property from the chris
object using the delete operator, the property no longer exists directly on the
specific object, causing the interpreter to look up the method from the prototype
chain, eventually finding Object.prototype .
When we turn our attention to property attributes, we will discuss some addi-
tional subtleties of the [[Put]] method.
7.1.3 Extending Objects through the Prototype Chain
By manipulating the prototype property of JavaScript constructors we can mod-
ify the behavior of every object created by it, including objects created before the
manipulation. This also holds for native objects, such as arrays. To see how this
works, we're going to implement a simple sum method for arrays. The test in
Listing 7.4 illustrates what we want to achieve.
Listing 7.4 Describing the behavior of Array.prototype.sum
TestCase("ArraySumTest", {
"test should summarize numbers in array": function () {
var array = [1, 2, 3, 4, 5, 6];
assertEquals(21, array.sum());
}
});
Running this test informs us that there is no sum method for arrays, which is
not all that surprising. The implementation is a trivial summarizing loop, as seen in
Listing 7.5.
 
Search WWH ::




Custom Search