简体   繁体   English

在ES6中,如何检查对象的类?

[英]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类的文字(例如StringNumber等),使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM