"Michael Winter" <m.******@blueyonder.co.invalid> wrote in message
news:ma*****************@text.news.blueyonder.co.u k...
On 25/05/2005 00:39, Roberto Sileoni wrote:
[snip]
function MyString() {
}
MyString.prototype = new String()
var a=new MyString("aaaaa");
alert(a.valueOf());
When i run this code on Firefox it raise an error like this:
String.prototype.valueOf called on incompatible object.
Certain predefined methods are considered generic; they can be used
with any object. For example, calling charAt (another String method)
on MyString should pose no problems as charAt will convert the
MyString instance to a string value, and then return the character at
the given offset.
Nope:
function MyString() { }
MyString.prototype = new String();
var a = new MyString("aaaaa");
alert(a.charAt(1)); // Line 14
Error: String.prototype.toString called on incompatible Object
Source File: file:///c:/DOCUME~1/grantw/LOCALS~1/Temp/hs~new.htm
Line: 14
The only solution to this is to wrap a String object inside your object
and expose the methods you want to allow on your object:
function MyString(newString) {
var s = newString;
this.charAt = function(n) { return s.charAt(n); }
}
var a = new MyString("aaaaa");
alert(a.charAt(1));
But if you're going to that, you might as well just write a factory
"class":
var MyStringFactory = new function() {
this.getInstance = function(newString) {
var s = new String(newString);
s.repeat = function(n) {
return (new Array(n + 1)).join(this);
}
s.trimRight = function() {
return this.replace(/\s$/, '');
}
s.trimLeft = function() {
return this.replace(/^\s/, '');
}
s.trim = function() {
return this.trimRight().trimLeft();
}
return s;
}
}();
var a = MyStringFactory.getInstance("abc");
alert(a.valueOf() + ';' + a.repeat(5));
This is probably something like how I'd do it. You can now "extend" the
String class however you want without sacrificing any built-in
functionality. Instead of making an object that "looks like" a String,
you're creating a String with additional properties/methods.
--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ -
http://jibbering.com/faq