javascript给类型添加方法
一、通过给Function.prototype增加方法来使得该方法对所有函数可用
Function.prototype.method = function(name,func){ if(!this.prototype[name]){ this.prototype[name] = func; return this; } }
通过上面的method方法给Number扩展一个取整的方法integer
Number.method('integer',function(){
return Math[this < 0 ? 'ceil' : 'floor'](this);
})
//调用一下
alert((5/2).integer());//返回2
给Sring扩展一个移除字符串末端空格的方法trim
String.method('trim',function(){
return this.replace(/^\s+|\s+$/g, '');
})
//试调一下
alert(" neat ".trim());//返回neat字符串

浙公网安备 33010602011771号