42

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
}
Ivan
  • 10,052
  • 12
  • 47
  • 78

2 Answers2

63

Can't you do person instanceof Person?

Comparing constructors alone won't work for subclasses

Eric
  • 95,302
  • 53
  • 242
  • 374
  • Yup, completely forgot about that! It works just like it would with functions (because the classes are just functions!). Thanks! – Ivan Mar 08 '15 at 02:42
  • 1
    this is not correct answer. if you have A,B,C classes and B & C extends A, then (new B()) instanceof C returns true. – someUser Jan 17 '17 at 16:17
  • 3
    @someUser: `new B() instanceof A` is the most reasonable definition of inheritance in javascript. If you're finding that you get that for `B` and `C`, then your issue is that you've actually made `B` inherit from `C` when you didn't intend to. How are you implementing your inheritance? – Eric Jan 17 '17 at 21:13
  • **Important**: `instanceof` does not do type checking the way that you expect similar checks to do in strongly typed languages. Instead, it does an identity check on the prototype object, and it’s easily fooled. It won’t work across execution contexts, for instance (a common source of bugs, frustration, and unnecessary limitations). For reference, an example in the wild, from bacon.js: https://github.com/baconjs/bacon.js/issues/296 – Sterling Bourne Aug 10 '17 at 18:38
  • @Noah: that sounds more like a warning about execution contexts, as the link discusses. You can construct an equivalent case in C++ with the same problem using `dynamic_cast` and classes within compilation units. So this does behave like strongly-typed languages, even if you don't expect that from them either. – Eric Aug 11 '17 at 02:18
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:

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

Refer to this thread for more info.

Community
  • 1
  • 1
galarant
  • 1,959
  • 19
  • 24