Subclassing JavaScript Native String

Just a quick post about subclassing native String constructor.
All we need is to redefine valueOf and toString methods.

function $String(__value__){
this.length = (this.__value__ = __value__ || "").length;
};
with($String.prototype = new String)
toString = valueOf = function(){return this.__value__};

With incoming V8, TraceMonkey, Squirrelfish, and other (if any ...) advanced engines that transforms repeated code into machine one, performances wont be a problem anymore and everybdy could create its own implementation of the String.

Of course, these statements will be preserved:

var s = new $String("abc");
s instanceof String; // true
s.constructor === String; // true

while typeof will return an object but we can easily use another method such:

$String.prototype.type = function(){
return "string";
};

alert(typeof s); // object
alert(s && s.type()); // string

concat as other native methods willl work, but returned object, unfortunatly, wont be a $String.

Comments

Popular posts from this blog

8 Things you should not be afraid of as a Developer

News

Why REST is so important