Ryan said:
Have read Douglas Crockfore's JavaScript The Good Parts, it recommend
Augmenting Types, e.g.
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
This is not a good thing.
The `method` method is not related to all Functions; only constructors.
It takes more time to comprehend that method than:-
MyConstructor.prototype.foo = fooFunc;
That method is unnecessary, not well named, adds overhead, adds clutter.
I criticized this part in another thread:
http://groups.google.com/group/comp...b741525ab6d/cd561210abc96faa#cd561210abc96faa
String.method('trim', function() {
return this.replace(/^\s+|\s+$/g, '');
});
No, it is not a good idea to replace a built-in method with a
hand-rolled version; not without good reason. In fact, without good
reason, that has some negative consequences.
String.prototype.trim is an ES5 standard method. It is implemented in
Tracemonkey (in Firefox).
A good reason for doing that would be, say, if an implementation did not
yet support the new method, or if it was shown to be buggy, but only
then after performing a /feature test/. The FAQ contains an example of
just that.
When Douglas wrote that, he probably did not consider the possibility
that String.prototype.trim would be added to the language.
The consequence of adding String.prototype.trim is that it replaces the
built-in String.prototype.trim with a user-defined version. That
user-defined version will not perform as fast as native code that it
replaced and will throw errors when used in a generic context.
| The following steps are taken:
| 1. Call CheckObjectCoercible passing the this value as its argument.
| 2. Let S be the result of calling ToString, giving it the this value
| as its argument.
| 3. Let T be a String value that is a copy of S with both leading and
| trailing white space removed. The definition of white space is the
| union of WhiteSpace and LineTerminator.
| 4. Return T.
|
| NOTE The trim function is intentionally generic; it does not require
| that its this value be a String object. Therefore, it can be
| transferred to other kinds of objects for use as a method.
The following are specified to work in ES5:
var trimFn = String.prototype.trim;
trimFn.call( window.getSelection() )
trimFn.call( new Error("You broke it.") );
trimFn.call( window.location );
trimFn.call( document.links[0] );
var range = document.createRange();
range.selectNode(document.body);
trimFn.call(range);
In Firefox, they correctly do convert the thisArt to string, as
specified by the standard.
However, when Douglas' method replaces that, it results in a TypeError.
By creating your own namespace, collisions like that can be avoided.