给类型添加方法
javascript中允许给基本类型添加方法。如:boolean、string、number
实例:在function中添加一个method函数,该函数为function添加其他自定义的函数(避免使用prototype),然后利用method函数想function中添加一个add函数,最后测试add函数在function中确实存在。该方法将func函数添加到function中,以name命名。然后,返回function的对象
function.prototype.method = function(name, func){
// 避免覆盖已有的方法
if(!this.prototype[name]){
this.prototype[name] = func;
}
return this;
};
// 通过function.method方法添加一个加法函数到function,该函数的名称为“add”
function.method("add", function(a, b){
if(typeof a != 'number' || typeof b != 'number'){
throw {
'name' : "typeerror",
'message' : "add方法必须传入数字"
};
}
return a + b;
});
// 调用function的add方法是否存在
(function(){
try{
alert(function.add(1, 3)); // 输出:4
} catch(e){
if(e.name === 'typeerror'){
alert(e.message);
}
}
})();
// 去除字符串两端的空白
string.method("trim", function(){
return this.replace(/^\s+|\s+$/g, '');
});
alert('|' + " hello world ".trim() + '|'); // 输出: '|hello world|'
// 添加数字的取整函数
number.method("integer", function(){
// 可以通过此种方式调用函数,如:math.random() == math['random']() == math["random"]()
return math[this < 0 ? 'ceil' : 'floor'](this);
});
alert((-10 / 3).integer()); // 输出:-3
以上就是如何给javascript类型添加方法实例详解的详细内容。