Using Function.prototype.method

Examples of Number and String prototyping

by peterbenoit

JavaScript

Function.prototype.method = function (name,func) {
    if(!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
}
    
Number.method('integer', function() {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

String.method('xify', function() {
    return (this).replace(/./gi, 'X');
});

String.method('trim', function() {
    return (this).replace(/^\s+|\s$/g, '');
});



console.log((-10 / 3).integer());
console.log("Peter".xify());
console.log("          trimming the verge           ".trim());