Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 335
Ivan Avatar asked Mar 08 '15 02:03

Ivan


People also ask

How do you check if an object is a class JS?

The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.

How do you define a class in ES6?

There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.

Are ES6 classes objects?

ECMAScript 2015, also known as ES6, introduced JavaScript Classes. JavaScript Classes are templates for JavaScript Objects.

How do you access a class in JavaScript?

Classes Are Functions Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class. We can access the [[Prototype]] of an object using the Object. getPrototypeOf() method.


2 Answers

Can't you do person instanceof Person?

Comparing constructors alone won't work for subclasses

like image 95
Eric Avatar answered Sep 20 '22 12:09

Eric


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.

like image 45
galarant Avatar answered Sep 21 '22 12:09

galarant