Enhances a JavaScript class by adding an is<Class> property to compare types between realms.
Motivation
Checking if a value is an instance of a class in JavaScript is not an easy task.
You can use instanceof, but that doesn't work between different realms or different versions. Comparing with constructor.name could be a solution but if you need to Uglify the module it doesn't work, as it creates different names for the same module.
const Person = require('package-x');const Animal = require('package-y');const diogo = new Person('Diogo', 'Porto');const wolf = new Animal('Gray Wolf');console.log(Person.isPerson(diogo));console.log(Person.isPerson(wolf));
Running the example above will print:
truefalse
ES5 and below classes:
In ES5 it's not unusual to see constructors like the one below, so you can call it without using the new keyword.
function Circle(radius) { if (!(this instanceof Circle)) { return new Circle(); } this.radius = radius;}
In such cases you can use the withIs.proto method:
const withIs = require('class-is');const Circle = withIs.proto(function (radius) { if (!(this instanceof Circle)) { return new Circle(); } this.radius = radius;}, { className: 'Circle', symbolName: '@org/package/Circle',});