wiki/content/20201113094246-javascript_instanceof_operator.md

935 B

date id title
2020-11-13 54c58f54-526f-4838-92c5-1a70d6b17a3c 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