<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.