Home >Web Front-end >JS Tutorial >Detailed explanation of how to add method instances to JavaScript types

Detailed explanation of how to add method instances to JavaScript types

伊谢尔伦
伊谢尔伦Original
2017-07-25 10:51:001760browse

Add methods to types
JavaScript allows adding methods to basic types. Such as: boolean, string, Number
Example: Add a method function in Function, which adds other custom functions to Function (avoid using prototype), then use the method function to add an add function to Function, and finally test The add function does exist in Function. This method adds the func function to Function and names it with name. Then, return the Function object

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

The above is the detailed content of Detailed explanation of how to add method instances to JavaScript types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn