JavaScript中Function.prototype和Object.prototype的区别
执行情况:1JavaScript中Function.prototype和Object.prototype的区别,javascript,string,object,prototype,Javascript,String,Object,Prototype,执行情况:1 Function.prototype.method = function (name,func){ this.prototype[name] = func; return this; }; String.method('trim', function(){ return this.replace(/^\s+|\s+$/g, ''); }); 执行情况:2 String.prototype.trim = function() { r
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
};
String.method('trim', function(){
return this.replace(/^\s+|\s+$/g, '');
});
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
1和2之间有什么区别吗?除了1可以应用于所有对象,2仅限于字符串对象 在这两种情况下,只有字符串对象将获得
trim
功能(即最终结果相同)。根据定义,第一个代码只是第二个代码的“捷径”(我用引号引起来,因为最终,代码长度和实现第一个方法的努力与第二个方法大致相同)。现代浏览器的更健壮、更通用的解决方案:
!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, ''); });
正如在引用的web站点中所解释的,此代码确保在迭代对象属性时正确隐藏该方法。它还仅在方法尚不存在时添加该方法
看