Search code examples
javascriptinheritanceprototypal-inheritance

Check inheritance of prototype, rather than instance


Lets say I have:

function Pet(){}
Pet.prototype.breathe = function(){}

And

function Cat(){}

I then go along and do:

Cat.prototype = Object.create(Pet.prototype)
Cat.prototype.purr = function(){}

I know I can check

var cat = new Cat()
console.log(cat instanceof Pet); //true

But how can I check if the function Cat is going to be an instance of Pet without instantiating it?

The most simple and hacky way I can think of is...

Pet.prototype.$$pet = true

And then check

console.log(Cat.prototype.$$pet) //true

But that doesn't seem very nice because I can just go along and do

Cat.prototype.$$pet = true

Solution

  • Turns out you can actually use

    Cat.prototype instanceof Pet
    

    MDN's examples of instanceof shows this

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof