467,886 Members | 1,773 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,886 developers. It's quick & easy.

new String( "foo" ) VS. "foo"

Why does "foo" instanceof String return false?

It just seems counterintuitive to me.

I mean, sure, I can always check the constructor:

var fooVar = "foo";

var isString = fooVar.constructor == String;

var isNotStringObject = fooVar instanceof String;

It seems counterintuitive to me that an object is not an instance of
it's constructor.

Garrett

Jul 12 '07 #1
  • viewed: 1943
Share:
1 Reply
<dh**********@gmail.comwrote in message
news:11**********************@k79g2000hse.googlegr oups.com...
Why does "foo" instanceof String return false?
String literals result in string primitive values and primitive values
are not objects.
It just seems counterintuitive to me.
Are you thinking of javascript as being in some way related to Java?
I mean, sure, I can always check the constructor:

var fooVar = "foo";

var isString = fooVar.constructor == String;
And let the type-converting side effects of the dot operator fool you
into thinking that - fooVar - might be an object?

Dot operators need their left-had side arguments to be objects so they
call the internal - ToObject - function with the retrieved value of that
operand as an argument. The internal - ToObject - function returns a
String object when its argument is a string primitive value and so with,
for example, the expression - "foo".indexOf('s') - the - "foo". - part
effectively evaluates to a string object equivalent to - new
String("foo") -, and it is this (internal and intermediate) object on
which the - indexOf - method is called.
var isNotStringObject = fooVar instanceof String;
Here the left operand for - instanceof - is the primitive value (no type
conversion is implied by - instanceof -) and as primitive values are not
objects the - String - constructor's - [[HasInstance]] - method will
return false in step 1 of its algorithm.
It seems counterintuitive to me that an object is not an
instance of it's constructor.
But makes perfect sense when you know that it is not an object at all.

Richard.

Jul 12 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by David Carroll | last post: by
68 posts views Thread by Marco Bubke | last post: by
2 posts views Thread by Manuel | last post: by
5 posts views Thread by Eric Lilja | last post: by
1 post views Thread by Alexnb | last post: by
reply views Thread by MrMoon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.