适用于现代浏览器的更强大和通用的解决方案:
!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, ''); });
如引用的网站中所述,此代码确保在迭代对象属性时正确隐藏该方法。如果一个方法不存在,它也只会添加该方法。
见http://jsfiddle.net/jstoolsmith/nyeeB/