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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28922435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:36:40  来源:igfitidea点击:

In ES6, how do you check the class of an object?

javascriptecmascript-6

提问by Ivan

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 typeofbecause the objects are still "object". Do I just compare constructors?

我不能只是使用,typeof因为对象仍然是"object". 我只是比较构造函数吗?

Example:

例子:

class Person {
  constructor() {}
}

var person = new Person();

if ( /* what do I put here to check if person is a Person? */ ) {
  // do stuff
}

回答by Eric

Can't you do person instanceof Person?

你不能person instanceof Person吗?

Comparing constructors alone won't work for subclasses

单独比较构造函数不适用于子类

回答by galarant

Just a word of caution, the use of instanceofseems prone to failure for literals of built-in JS classes (e.g. String, Number, etc). In these cases it might be safer to use typeofas follows:

谨慎的只是一个字,使用的instanceof似乎容易出现故障的内置JS类(如文字StringNumber等等)。在这些情况下,使用typeof以下方法可能更安全:

typeof("foo") === "string";

typeof("foo") === "string";

Refer to this threadfor more info.

有关更多信息,请参阅此线程