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 }
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.
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.
ECMAScript 2015, also known as ES6, introduced JavaScript Classes. JavaScript Classes are templates for JavaScript Objects.
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.
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 (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With