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

D

dhtmlkitchen

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
 
R

Richard Cornford

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.
 

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
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top