extend Object/String/Number/Array using prototype
Object.prototype.foo = 10;
console.log(foo); // 10
// 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!!!