I've read the book too, but in my version (2008 in Portuguese) that
function is slightly different, with one very important feature test:
My English copy of the book (2008, first edition) lists the OP's
version of the code, and then later in the same section lists the one
you supply, introduced by "The prototypes of the basic types are
public structures, so care must be taken when mixing libraries. One
defensive technique is to add a method only if the method is known to
be missing."
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
};
Clearly this is an improvement on the original. I agree with whoever
mentioned that this should have a verb, "setMethod", "addMethod", or
some such.
I don't much like modifying the prototypes of the built-in objects,
although I understand that it can be useful and powerful to do so in
at least some circumstances. But Crockford's only justification for
this is only that "[W]e no longer have to type the name of the
prototype property. That bit of ugliness can now be hidden." His
original version (as supplied by the OP) seems to have no advantage.
I certainly don't see that this:
Number.method('integer', function () {
return Math[this < 0 : 'ceil' : 'floor'](this);
});
is any less ugly than this:
Number.prototype.integer = function () {
return Math[this < 0 : 'ceil' : 'floor'](this);
};
But when you add in the error checking, it is clearly less ugly than
this:
if (!Number.prototype.integer) {
Number.prototype.integer = function () {
return Math[this < 0 : 'ceil' : 'floor'](this);
};
}
So I think a version of this technique would be useful if you do
choose to enhance these prototypes.
-- Scott