Fun with Stamps. Episode 22. JavaScript instanceof as composable stamp

Vasyl Boroviak
3 min readApr 10, 2018

Hello. I’m developer Vasyl Boroviak and welcome to the twenty second episode of Vasyl Boroviak presents Fun with Stamps.

TL;DR: This is always false myObj instanceof MyStamp === false. But it will become true if you compose @stamp/instanceof to MyStamp.

Occasionally people ask:

How would I check if object is an instance of a particular stamp?

It is not recommended to use instanceof in JavaScript in general. It’s dangerous. Especially with stamps. However, old habits die hard so we developed @stamp/instanceof utility stamp.

The instanceof always returns false for any stamp and object out there.

let MyStamp = stampit({ ... }) // you have a stamp
let myObj = MyStamp() // create instance of your stamp
console.log(myObj instanceof MyStamp) // false

But after composing InstanceOf utility stamp into your stamp the instanceof works as if you were using classes.

const InstanceOf = require('@stamp/instanceof')
MyStamp = MyStamp.compose(InstanceOf) // compose it into your stamp
myObj = MyStamp() // create instance of your stamp
console.log(myObj instanceof MyStamp) // true

Behind the scenes

Here is the full source code of the @stamp/instanceof utility stamp.

As you can see, we are using the well-known Symbol “hasInstance”. If you apply it to a function (stamps are functions) then JavaScript runtime will use your implementation of instanceof instead of the default one.

const compose = require('@stamp/compose');

const stampSymbol = Symbol.for('stamp');

module.exports = compose({
methods: {},
composers: [({ stamp }) => {
// Attaching to object prototype to save memory
stamp.compose.methods[stampSymbol] = stamp;

Object.defineProperty(stamp, Symbol.hasInstance, {
value (obj) {
return obj && obj[stampSymbol] === stamp;
}
});
}]
});

We are using the composers feature here. Every time a composition happens we attach the “stamp” symbol to prototype (aka methods metadata). Then we attach our instanceof implementation to the stamp. The implementation tries to retrieve the “stamp” symbol value from an object and compare it with the stamp.

Reminder. There is stampit_org twitter where we publish all the news.

Have fun with stamps!

--

--