开发者

javascript isInstanceOf [duplicate]

This question already has answers here: 开发者_StackOverflow Closed 11 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜