[英]In ES6, how do you check the class of an object?
In the ES6, if I make a class and create an object of that class, how do I check that the object is that class? 在ES6中,如果我创建一个类并创建该类的对象,我该如何检查该对象是否是该类?
I can't just use typeof
because the objects are still "object"
. 我不能只使用
typeof
因为对象仍然是"object"
。 Do I just compare constructors? 我只是比较构造函数吗?
Example: 例:
class Person {
constructor() {}
}
var person = new Person();
if ( /* what do I put here to check if person is a Person? */ ) {
// do stuff
}
Can't you do person instanceof Person
? 你不能
person instanceof Person
吗?
Comparing constructors alone won't work for subclasses 单独比较构造函数不适用于子类
Just a word of caution, the use of instanceof
seems prone to failure for literals of built-in JS classes (eg String
, Number
, etc). 需要注意的是,对于内置JS类的文字(例如
String
, Number
等),使用instanceof
似乎很容易失败。 In these cases it might be safer to use typeof
as follows: 在这些情况下,使用
typeof
可能更安全,如下所示:
typeof("foo") === "string";
Refer to this thread for more info. 有关详细信息,请参阅此主题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.