时间:2021-07-01 10:21:17 帮助过:4人阅读
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类型添加方法实例详解的详细内容,更多请关注Gxl网其它相关文章!