给类型添加方法
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类型添加方法实例详解的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号