Fun with Instanceof

Saturday, June 8th @ 7:14 pm CDT

I don't know how I overlooked it for so long, but it comes up pretty regularly that I need a way to tell if an object in JavaScript is a particular kind of object derived from a known class. Here's a simple example of how it plays out for classes, as well as extending classes.

class Foo {
  constructor() {}
}

class Bar extends Foo {
  constructor() {
    super()
  }
}

const f = new Foo()
const b = new Bar()

console.log(`false is a Foo:  ${false instanceof Foo}`)
console.log(`'Blah' is a Foo: ${'Blah' instanceof Foo}`)
console.log(`f is a Foo:      ${f instanceof Foo}`)
console.log(`f is a Bar:      ${f instanceof Bar}`)
console.log(`b is a Foo:      ${b instanceof Foo}`)
console.log(`b is a Bar:      ${b instanceof Bar}`)

The contents of the file above result in the following output:

"false is a Foo:  false"
"'Blah' is a Foo: false"
"f is a Foo:      true"
"f is a Bar:      false"
"b is a Foo:      true"
"b is a Bar:      true"

Fun with Instanceof on Codepen

While playing around with this, I also had a little fun with learning about adding methods to the prototype, and learned how to do things that could potentially veer off into Rails-y territory. For example, the following helper method that can be used on any value in your code to determine if it's derived from a specific class. The output from the following code would be the same as above.

Object.prototype.isA = function (objectType) {
  return this instanceof objectType
}

console.log(`false is a Foo:  ${false.isA(Foo)}`)
console.log(`'Blah' is a Foo: ${'Blah'.isA(Foo)}`)
console.log(`f is a Foo:      ${f.isA(Foo)}`)
console.log(`f is a Bar:      ${f.isA(Bar)}`)
console.log(`b is a Foo:      ${b.isA(Foo)}`)
console.log(`b is a Bar:      ${b.isA(Bar)}`)

Fun with Instanceof 2 on Codepen

This was a fun learning exercise, but also comes in quite handy frequently when building things in JavaScript and TypeScript. Happy hacking!