Skip to content

Instantly share code, notes, and snippets.

@curtis1000
Created May 20, 2013 21:38
Show Gist options
  • Save curtis1000/5615788 to your computer and use it in GitHub Desktop.
Save curtis1000/5615788 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment