The one part of the book that makes me cringe is Douglas' augmentation of built-in prototypes. He provides multiple examples like defining
String.prototype.trim is very likely to cause a collision. Douglas has expounding many times on his enthusiasm for mashups where this type of collision is most likely and which doubles the perplexity of his practice of augmenting built-in objects.
I've challenged Douglas about this augmentation practice on the JSON mailing list because in his
json2.js program he augments
Date.prototype.toJSON. This augmentation appears completely gratuitous. Rewriting the
json2.js file to not use augmentation is trivial and results in a more resilient program. Douglas' response to my challenge was
"Augmentation of the core objects is one of the places where we can effectively repair the language. It should not be done carelessly. I think this is a good use. It will likely be built into the next edition of the standard."
I don't think the language is anywhere near "broken" in this case. It is simply missing a
Douglas' use of augmentation seems antithetical to one of his books main themes of "global abatement" to avoid collisions in the global namespace. One of his global abatement techniques is a common one where a single global object is used as a pseudo namespace like
dojo. Douglas describes that using a global object this way "significantly reduces the chance of bad interactions with other applications, widgets or libraries." Yet he causes almost certain bad interaction by augmenting
ca_michaux_addListener where the
ca_michaux part partitions all my names away from everyone else's. For Dojo they are relatively safe with
dojo.connect for the same job.
In browser scripting, we define names in many different spaces as the browser is effectively a framework and we attach names where needed. For example, if we create an HTML form with a
name attribute then we are augmenting the
document.forms object. For safe namespacing, it would be prudent for me to give my forms names like
document.forms than there is augmenting
String.prototype, is there? (Augmenting
Object.prototype is still bad because it breaks
for in loops and using
hasOwnProperty inside these loops does not fix all the problems.)
String.prototype is these are public spaces and we need to augment by defining names with care to avoid collisions. If I define my trim function as
String.prototype.ca_michaux_trim then, for practical purposes, that should be safe from a collision. It should be just as safe as if I define a global function
We certainly cannot claim our programs are safe if we just go around willy-nilly defining generic names in public namespaces. Douglas may not be wrong that augmenting built-in prototypes is ok but his examples are not doing it in a responsible and resilient manner.
Have something to write? Comment on this article.