给类型增加方法 Argumenting Types
可以通过Function.prototype增加方法,使得方法对所有函数可用
//通过Function.prototype增加一个method方法,我们不必键入prototype这个属性名,就可以为一个对象创建方法了
//给基本类型增加方法,可以大大增加JS的表现力
/*基本类型的原型是公共的结构,因此在添加时首先确定下没有此方法*/
Function.prototype.method = function(name,func){
if(!this.prototype[name]){
this.prototype[name] = func;
}
return this;
}
?针对number类型的数字取整数 (JS自带的取整方法丑陋,这里可以添加一个取证方法)
Number.method('integer',function(){
return Math[this<0 ? 'ceil' : 'floor'](this);
});
function integerMethod(){
var result = (-10/3).integer();
document.getElementById("ArgumentingId").innerHTML = result;
}
?JS 缺少一个移除字符串末端空白的方法。??
String.method('trim',function(){
return this.replace(/^\s+|\s+$/g,'');
})
function trimMethod(){
var str = '123 ';
// str = "|"+str+"|";
str = "|"+str.trim()+"|";
document.getElementById("ArgumentingId2").innerHTML = str;
}
?html代码
<button onclick="integerMethod();">增加方法integer</button>
<div id='ArgumentingId'></div>
<button onclick="trimMethod();">增加方法trim</button>
<div id='ArgumentingId2'></div>
?
?
?
