javascript isInstanceOf

11 浏览
0 Comments

javascript isInstanceOf

这个问题已经有了答案:

可能的重复:

如何检测变量是否为字符串

x = 'myname';
x.intanceOf == String

为什么第二个语句返回false?如何检查一个变量是否为字符串?

admin 更改状态以发布 2023年5月21日
0
0 Comments

使用instanceOf可能并不是一个好主意。

typeof操作符(连同instanceof)可能是JavaScript中最大的设计缺陷,因为它几乎完全失效了。

请参见:http://bonsaiden.github.com/JavaScript-Garden/#types.typeof

相反,请使用 Object.prototype.toString,像这样:

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
0 Comments

这是错误的,因为intanceOfundefined,而不是对String构造函数的引用。

instanceOf是一个运算符,而不是一个实例方法或属性,使用方式如下:

 "string" instanceof String

但是,这将返回false,因为字面上的字符串不是使用String构造函数创建的String对象

所以您真正想做的是使用type运算符。

typeof "string" == "string"

0