Skip to content

Instantly share code, notes, and snippets.

@easierbycode
Created February 24, 2012 23:02
Show Gist options
  • Save easierbycode/1904402 to your computer and use it in GitHub Desktop.
Save easierbycode/1904402 to your computer and use it in GitHub Desktop.
extend Object/String/Number/Array using prototype
// all objects inherit methods and properties from Object.prototype, although they may be overridden
Object.prototype.toSource()
// "({})"
str = 'hello';
arr = new Array(20);
num = 99;
Object.prototype.boom = function() {
return 'pow';
};
Number.prototype.boom = function() {
return NaN;
}
console.log(str.boom()); // pow
console.log(arr.boom()); // pow
console.log(num.boom()); // NaN
String.prototype.myFooProp = 'dingle';
console.log( arr.myFooProp ); // undefined
console.log( str.myFooProp ); // dingle
Object.prototype.whatAmI = function() {
if (this.constructor == Array) {
return "I'm an array!!!";
}
if (this.constructor === String) {
return "I'm a string!!!";
}
};
console.log( arr.whatAmI() ); // I'm an array!!!
console.log( str.whatAmI() ); // I'm a string!!!
Object.prototype.foo = 10;
console.log(foo); // 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment