Implementation: 1
Function.prototype.method = function (name,func){ this.prototype[name] = func; return this; }; String.method('trim', function(){ return this.replace(/^\s+|\s+$/g, ''); });Implementation: 2
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
Is there any difference between 1 and 2? except that 1 can be applied to all objects and 2nd is only limited to String objects.
2 Answers 2
In both cases only String objects will get the trim function (i.e. the end result will be identical). The first code, as defined, is only a "shortcut" to the second code (I put it in quotes because, in the end, the code length and the effort to implement the first method is roughly the same as the second method).
Comments
A more robust and generic solution for modern browsers :
!Object.implement && Object.defineProperty (Object.prototype, 'implement', {
// based on http://www.websanova.com/tutorials/javascript/extending-javascript-the-right-way
value: function (mthd, fnc, cfg) { // adds fnc to prototype under name mthd
if (typeof mthd === 'function') { // find mthd from function source
cfg = fnc, fnc = mthd;
(mthd = (fnc.toString ().match (/^function\s+([a-z$_][\w$]+)/i) || [0, ''])[1]);
}
mthd && !this.prototype[mthd] &&
Object.defineProperty (this.prototype, mthd, {configurable: !!cfg, value: fnc, enumerable: false});
}
});
// Allows you to do
String.implement (function trim () { return this.replace(/^\s+|\s+$/g, ''); });
As explained in the referenced web site, this code ensures that the method is properly hidden when iterating over the object properties. It also only adds the method if one does not already exist.