curtis1000
5/20/2013 - 9:38 PM

Playing with JavaScript prototypes

Playing with JavaScript prototypes

// all objects inherit from Object.prototype,
// we can add capabilities like so:

console.log('adding capabilities to Object.prototype');

if (typeof Object.prototype.totalBills != 'function') {
    Object.prototype.totalBills = function () {
        if (this.bills && this.bills.constructor === Array) {
            var total = 0;
            for (var i=0; i<this.bills.length; i++) {
                if (typeof this.bills[i] === 'number') {
                    total += this.bills[i];
                }
            }
            return total;
        }
    };
}

var myObj = {
    name: 'Curtis',
    bills: [100,200,300,1000]
};

console.log('total bills: ' + myObj.totalBills());

// arrays
var myArray = ['woopty','freakin','doo'];

// checking for the array type
console.log('checking for the array type');

// typeof outputs 'object', because arrays are objects, not helpful here
console.log('typeof myArray: ' + typeof myArray);

// checking against the constructor is the correct way
console.log('(myArray.constructor === Array): ' + (myArray.constructor === Array));

// extending Array.prototype
console.log('adding capabilities to Array.prototype');

if (typeof Array.prototype.addSomething != 'function') {
    Array.prototype.addSomething = function () {
        this.push('something');
    };
}

myArray.addSomething();
console.log(myArray);