Checking instance type with instanceOf
There are many situations, such as argument validation, where we'll want to check the class of an object. Because JavaScript is not statically typed, we can't guarantee that a function receives an argument of the correct type before the program starts, and we need to check at runtime.
In this recipe, we'll see how to use the instanceOf
operator to check an object's prototype at runtime.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
07-04-checking-with-instanceof
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
with two identical classes,Rocket
andInactiveRocket
:
// main.js class Rocket { constructor(name) { this.name = name; } } class InactiveRocket { constructor...