HTML and CSS Reference
In-Depth Information
Listing 7.5 Adding a method to Array.prototype
Array.prototype.sum = function () {
var sum = 0;
for(vari=0,l=this.length; i < l; i++) {
sum += this[i];
return sum;
Because all arrays inherit from Array.prototype , we're able to add
methods to all arrays. But what happens if there already is a sum method for
arrays? Such a method could be provided by a given browser, a library or other
code running along with ours. If this is the case, we're effectively overwriting that
other method. Listing 7.6 avoids this by placing our implementation inside an if
test that verifies that the method we're adding does not already exist.
Listing 7.6 Defensively adding a method to Array.prototype
if (typeof Array.prototype.sum == "undefined") {
Array.prototype.sum = function () {
// ...
In general, this is a good idea when extending native objects or otherwise
working on global objects. This way we make sure our code doesn't trip up other
code. Even so, if there already is a sum method available, it may not act the way we
expect, causing our code that relies on our sum to break. We can catch these errors
with a strong test suite, but this kind of problem clearly indicates that relying on
extensions to global objects may not be the best approach when the focus is writing
robust code.
7.1.4 Enumerable Properties
Extending native prototypes like we just did comes with a price. We already saw
how this may lead to conflicts, but there is another drawback to this approach.
When adding properties to an object, they are instantly enumerable on any instance
that inherits it. Listing 7.7 shows an example of looping arrays.
Search WWH ::

Custom Search