首頁  >  文章  >  web前端  >  如何為javascript類型添加方法實例詳解

如何為javascript類型添加方法實例詳解

伊谢尔伦
伊谢尔伦原創
2017-07-25 10:51:001703瀏覽

為類型新增方法
    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