Skip to content

Instantly share code, notes, and snippets.

@xcambar
Created October 18, 2011 08:44
Show Gist options
  • Save xcambar/1294949 to your computer and use it in GitHub Desktop.
Save xcambar/1294949 to your computer and use it in GitHub Desktop.
String prototype extension fail!
/**
* Comparing a String object and a simple string
**/
var myStringSimple = 'abcd';
console.log(myStringSimple instanceof String); // false
console.log(typeof(myStringSimple)); // 'string'
var myStringObject = new String('abcd');
console.log(myStringSimple instanceof String); // true
console.log(typeof(mySimpleString)); // 'object'
// BUT: all the methods from String.prototype are available to myStringSimple
String.prototype.test = function () {
console.log(1);
};
'xyz'.test(); // 1 is output to the console
// Why ? Because internally it's (new String('xyz')).test() that is executed
myStringSimple == myStringObject; //true (thanks to type coercion)
myStringSimple === myStringObject; //false
/************************************************************************************************/
/**
* Pitfalls of augmenting the prototype of String
**/
String.prototype.test = function () {
console.log(1);
};
var myString = new String('abcd');
//Looping over the elements of myString
for (var index in myString) {
console.log(index, myString[index]);
}
//// => returns
// 0 a
// 1 b
// 2 c
// 3 d
// test function () { console.log(1); }
// => The enumerability of String happens on the string 'abcd' + the augmented prototype methods!!
/************************************************************************************************/
/**
* Pitfalls of inheriting String.prototype
**/
var ExtString = function () {
String.apply(this, arguments); //arguments is the JS notation for argv
};
ExtString.prototype = String.prototype; // ExtString.prototype = new String(); is equivalent
ExtString.prototype.extTest = function () {
console.log('my inheritance Test');
};
var myExtString = new ExtString('123456789');
console.log(myExtString.length); // 0
// => Fail...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment