Possible Duplicate:
how to detect if variable is a string
x = 'myname';
x.intanceOf == String
why does the second statement returns false ? how can i check if a variable is string or not ?
Possible Duplicate:
how to detect if variable is a string
x = 'myname';
x.intanceOf == String
why does the second statement returns false ? how can i check if a variable is string or not ?
It is false because intanceOf
[sic] is undefined
, not a reference to the String
constructor.
instanceOf
is an operator, not an instance method or property, and is used like this:
"string" instanceof String
But this will return false as the literal string is not a String object
created using the String
constructor.
So what you really want to do is use the type
operator
typeof "string" == "string"
Using instanceOf might not be a good idea after all.
The typeof operator (together with instanceof) is probably the biggest design flaw of JavaScript, as it is near of being completely broken.
See: http://bonsaiden.github.com/JavaScript-Garden/#types.typeof
Instead use Object.prototype.toString like so:
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
is('String', 'test'); // true
is('String', new String('test')); // true