JS: Good parts - Ch.4 - Functions

augmenting types

by Denise Nepraunig

JavaScript

/* 
All texts and infos I have taken from:
'JavaScript: The Good Parts' by Douglas Crockford
*/

// AUGMENTING types
// by aumenting Function.prototype we  can make a method
// available to all function

Function.prototype.method = function (name, func) {
    // only add the method of it doesn't alread exist
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// by augmenting Function.prototype with a method method, we no
// longer have tot ype the name of the prototpye property

// let's convert a number into an integer
Number.method('integer', function () {
    console.log("hello");
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

console.log("we expect -3", (-10 / 3).integer()); // -3

// and now let's invent a function that trims strings
// it removes spaces from the end of a string
var myString = "I have whitespace     ";
console.log("length of myString", myString.length);

String.method('trim', function () {
    return this.replace(/^\s+|\s+$/g, '');
});
console.log("length of trimmed string", myString.trim().length);