一個更強大和通用的解決方案:
!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/
來源
2012-06-16 06:47:48
HBP
謝謝你的幫忙! – R2D2