String object question

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

<html>
<head>
<script>
var s=String( 'foo' );
alert( s );
s.bar='bar';
alert( s.bar );
</script></head></html>

Why does the second alert produce 'undefined'? Are string objects
somehow special?
 
L

Lee

Christopher Benson-Manica said:
<html>
<head>
<script>
var s=String( 'foo' );
alert( s );
s.bar='bar';
alert( s.bar );
</script></head></html>

Why does the second alert produce 'undefined'? Are string objects
somehow special?

You didn't create a String object, just a simple string.
Try it with:

var s = new String( 'foo' );
 
P

PDannyD

Christopher said:
<html>
<head>
<script>
var s=String( 'foo' );
alert( s );
s.bar='bar';
alert( s.bar );
</script></head></html>

Why does the second alert produce 'undefined'? Are string objects
somehow special?

Shouldn't it be something like this?

<html>
<head>
<script>
var s=new String();
s.first = "First string";
alert(s.first);
s.second = "Second string";
alert(s.second);
</script>
</head>
</html>
 
C

Christopher Benson-Manica

Lee said:
You didn't create a String object, just a simple string.
Try it with:
var s = new String( 'foo' );

Yes, that works. Here's a followup question though: Does the split()
method produce an array of string objects or primitive strings?
 
L

Lee

Christopher Benson-Manica said:
Yes, that works. Here's a followup question though: Does the split()
method produce an array of string objects or primitive strings?

They are primitive strings.
The following alerts "string", rather than "object":

<html>
<body>
<script type="text/javascript">
var token="alpha,beta,gamma".split(",");
alert(typeof token[0]);
</script>
</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top