473,466 Members | 1,443 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Prototype behavior

While i was trying to understand prototype behavior,
i wrote this sample code:

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.

Can someone help me to understand what happens and why this code
does not work.

Thanks a lot and sorry for my english.

Jul 23 '05 #1
4 2102
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.

However, some methods are not transferable; if they are called from an
object that is not of the correct type, the ECMAScript engine with throw
a TypeError exception. The String.prototype.valueOf method is one such
non-transferable method.

User-defined objects, such as MyString, will always be Object instances.
You can give them prototypes of other built-in types, but they will
still be Objects.

[snip]

Does that help at all?

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
"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
Jul 23 '05 #3
On 25/05/2005 16:31, Grant Wagner wrote:
"Michael Winter" <m.******@blueyonder.co.invalid> wrote in message
news:ma*****************@text.news.blueyonder.co.u k...


[snip]
Certain predefined methods are considered generic; they can be used
with any object. [...]


Nope:

function MyString() { }
MyString.prototype = new String();
var a = new MyString("aaaaa");
alert(a.charAt(1)); // Line 14


You aren't providing any mechanism to get at that value passed to the
constructor. The Object.prototype.toString method that would be used by
String.prototype.charAt no longer exists on that object. Instead, it
would use String.prototype.toString, which, like
String.prototype.valueOf, is a non-transferable method.

If you change the constructor to:

function MyString(value) {
this.toString = function() {return value;};
}

then the charAt method works just fine.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
"Michael Winter" <m.******@blueyonder.co.invalid> wrote in message
news:ni*****************@text.news.blueyonder.co.u k...
On 25/05/2005 16:31, Grant Wagner wrote:
"Michael Winter" <m.******@blueyonder.co.invalid> wrote in message
news:ma*****************@text.news.blueyonder.co.u k...


[snip]
Certain predefined methods are considered generic; they can be used
with any object. [...]


Nope:

function MyString() { }
MyString.prototype = new String();
var a = new MyString("aaaaa");
alert(a.charAt(1)); // Line 14


You aren't providing any mechanism to get at that value passed to the
constructor. The Object.prototype.toString method that would be used
by String.prototype.charAt no longer exists on that object. Instead,
it would use String.prototype.toString, which, like
String.prototype.valueOf, is a non-transferable method.

If you change the constructor to:

function MyString(value) {
this.toString = function() {return value;};
}

then the charAt method works just fine.


Hmm. Well in that case:

function MyString(value) {
if (value == null) {value = 'blah';}
this.toString = function() {return value;}
this.valueOf = function() {return value.valueOf();}
}
MyString.prototype = new String();
var s = new MyString(0);
alert(s.valueOf());

However, you still need to wrap any other methods and properties that
won't work properly (like I did with valueOf()). It also just occurred
to me that in my "factory class" example you don't need
a -MyStringFactory- at all:

String.getInstance = function(newString) {
var s = new String(newString);
// ...
}
var s = String.getInstance("abc");
Decisions, decisions. I think I still lean towards having a factory
method on the String object rather than creating a new custom object
type but I'll have to think about it a bit.

--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Robert | last post by:
Hi, I can use "with" like this: function MyObject(message) { this.message = message; } function _MyObject_speak() {
2
by: chuck | last post by:
Hello, I am using the prototype.js http://prototype.conio.net library for a project and so wanted to use the Insertion function to replace text within a table. I want to simply replace what is...
9
by: Neelesh | last post by:
Hi all, it is strange that the following code compiles and runs (tested with g++ 3.4.2) #include <iostream> using namespace std; int main(int a, int b, int c, int d, int e) { cout <<...
14
by: Mantorok Redgormor | last post by:
Would this by any chance invoke undefined behavior? extern int printf(const char *, ...); int main(void) { printf("Hello\n"); return 0; } That is, providing my own printf prototype would...
8
by: Csaba Gabor | last post by:
Is there any way in Mozilla/Firefox to add an event listener to all textarea elements? Something along the lines of HTMLTextAreaElement.prototype.onkeydown = function() {alert('mom');} only it...
2
by: VJ | last post by:
I tried to write sample code to get understanding of javascript's prototypal inheritance (along with the variety of function calling choices.. ) During the process, I got myself throughly...
3
by: Rakesh UV | last post by:
Hi, If i am not putting the function prototype of a function returning a pointer, i get a core dump.Though this will happen less probably on 32 bit machine example int main(int argc , char...
3
by: kj | last post by:
OK, here's another construct I've run into in the jQuery source that I can't figure out. It looks like this: return new jQuery.prototype.init( selector, context ); So basically, as far as I...
83
by: liketofindoutwhy | last post by:
I am learning more and more Prototype and Script.aculo.us and got the Bungee book... and wonder if I should get some books on jQuery (jQuery in Action, and Learning jQuery) and start learning about...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.