JavaScript Instanceof Operator
Description
Sometimes you want to know whether an
object was derived from a specific
class. To do this one can use the
instanceof
operator.
Syntax
class Parent {
constructor(name, parentChild = "Parent") {
this.parentChild = parentChild
this.name = name
}
speak(line) {
console.log(`${this.parentChild} ${this.name} says '${line}'`)
}
}
class Child extends Parent {
constructor(name) {
super(name, "Child")
}
}
let parent = new Parent("Father")
let child = new Child("Gregory")
console.log(parent instanceof Parent) // true
console.log(parent instanceof Child) // false
console.log(child instanceof Parent) // true
console.log(child instanceof Child) // true