Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Way to test which "sibling class" an object is in Javascript?

Say I have a base class "Pet" and child classes "Dog" and "Cat". Is there a generic way I can take an arbitrary object I know is a "Pet" and test to see if it is "Dog" or "Cat"?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can either ask the object for its constructor.name property, or if you have a reference to the class, you can use the instanceof operator:

class Pet {
  constructor(name) {
    this.name = name;
  }
}

class Cat extends Pet {
  sayHello() { console.log(`${this.name} miaows`) }
}

class Dog extends Pet {
  sayHello() { console.log(`${this.name} barks`) }
}

const goofy = new Dog('Pluto');
const garfield = new Cat('Garfield');

console.log(goofy.constructor.name);
console.log(garfield.constructor.name);
console.log(goofy instanceof Dog);
console.log(garfield instanceof Cat);

Please note that Pet shouldn't know about the existence of Dog or Cat (and also neither of the latter two should know anything about the existence of the other).

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!