首页  >  文章  >  web前端  >  如何给javascript类型添加方法实例详解

如何给javascript类型添加方法实例详解

伊谢尔伦
伊谢尔伦原创
2017-07-25 10:51:001701浏览

给类型添加方法
    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 ? &#39;ceil&#39; : &#39;floor&#39;](this);
});
alert((-10 / 3).integer()); // 输出:-3

以上是如何给javascript类型添加方法实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn