The next best thing to inheriting from an intrisic class is inheriting from a class that behaves in the same manner. If a class exists that implements all the properties and methods of another class and in the same way, then this class could be substituted for the other.
var s = "Hello World";
var n = s.length; // n becomes 11
var s2 = s.substr(6); // s2 becomes "World"
alert(s); // pops up a message box with "Hello World"
var s3 = 'Msg: ' + s; // s3 becomes "Msg: Hello World"
To create a wrapper class that can simulate a String, all that's needed is to support the property and the methods:
// String wrapper class
// store the value
this.String = value;
// support the length property
this.length = this.String.length;
StringWrapper.prototype.substr = function(start, length)
New StringWrapper instances can be created with the new operator:
var s = new StringWrapper("Hello World");
The StringWrapper has almost everything it needs to simulate the real String instance in the code snippet above. It's constructed with a string value which is stored under a property called "String". The length property is supported by assigning its value in advance during the constructor. Since the String contents don't change during the lifetime of the StringWrapper, the string length will remain constant as well. The substr function simply calls into the String version with the supplied arguments.
There is still a problem with the StringWrapper class as it stands. If a StringWrapper instance is passed to the alert() function, the resulting window will not display "Hello World" as expected but something like "[object Object]". The reason for this is that when alert() is called, it will first call toString() on the argument to translate it into string form so that it can be displayed. The StringWrapper class must implement this function...
StringWrapper.prototype.toString = function()
StringWrapper.prototype.valueOf = function()