简体   繁体   中英

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?

I can't just use typeof because the objects are still "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 ?

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). In these cases it might be safer to use typeof as follows:

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

Refer to this thread for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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