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"
. Do I just compare constructors?
我不能只使用typeof因为对象仍然是“对象”。我只是比较构造函数吗?
Example:
class Person {
constructor() {}
}
var person = new Person();
if ( /* what do I put here to check if person is a Person? */ ) {
// do stuff
}
3 个解决方案
#1
49
Can't you do person instanceof Person
?
你不能做人的实例吗?
Comparing constructors alone won't work for subclasses
单独比较构造函数不适用于子类
#2
6
Just a word of caution, the use of instanceof
seems prone to failure for literals of built-in JS classes (e.g. String
, Number
, etc). In these cases it might be safer to use typeof
as follows:
需要注意的是,使用instanceof似乎很容易导致内置JS类的文字失败(例如String,Number等)。在这些情况下,使用typeof可能更安全,如下所示:
typeof("foo") === "string";
typeof(“foo”)===“string”;
Refer to this thread for more info.
有关详细信息,请参阅此主题。
#3
-3
in case of ecmascript-6 classes inheritance: lets say class A is base for B and C, then neither instanceof nor typeof will work correctly, as
在ecmascript-6类继承的情况下:假设类A是B和C的基础,那么instanceof和typeof都不会正常工作,如
(new B()) instanceof C // is true
will return true. For this case, I am doing:
将返回true。对于这种情况,我正在做:
(new B()).constructor == B
Edit: instanceof works for mentioned case as well, my example code had issue.
编辑:instanceof也适用于上述案例,我的示例代码有问题。
#1
49
Can't you do person instanceof Person
?
你不能做人的实例吗?
Comparing constructors alone won't work for subclasses
单独比较构造函数不适用于子类
#2
6
Just a word of caution, the use of instanceof
seems prone to failure for literals of built-in JS classes (e.g. String
, Number
, etc). In these cases it might be safer to use typeof
as follows:
需要注意的是,使用instanceof似乎很容易导致内置JS类的文字失败(例如String,Number等)。在这些情况下,使用typeof可能更安全,如下所示:
typeof("foo") === "string";
typeof(“foo”)===“string”;
Refer to this thread for more info.
有关详细信息,请参阅此主题。
#3
-3
in case of ecmascript-6 classes inheritance: lets say class A is base for B and C, then neither instanceof nor typeof will work correctly, as
在ecmascript-6类继承的情况下:假设类A是B和C的基础,那么instanceof和typeof都不会正常工作,如
(new B()) instanceof C // is true
will return true. For this case, I am doing:
将返回true。对于这种情况,我正在做:
(new B()).constructor == B
Edit: instanceof works for mentioned case as well, my example code had issue.
编辑:instanceof也适用于上述案例,我的示例代码有问题。