Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to add method instances to JavaScript types

伊谢尔伦
Release: 2017-07-25 10:51:00
Original
1710 people have browsed it

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!