class-is
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.
Symbols to the rescue!
Installation
$ npm install class-is
If you want to use this module in the browser you have to compile it yourself to your desired target.
Usage
ES6 classes:
// Package Xconst withIs = ; { thisname = name; thiscity = city; } moduleexports = ;
// Package Yconst withIs = ; { thisspecies = species; } moduleexports = ;
const Person = ;const Animal = ; const diogo = 'Diogo' 'Porto';const wolf = 'Gray Wolf'; console;console;
Running the example above will print:
true
false
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.
{ if !this instanceof Circle return ; thisradius = radius;}
In such cases you can use the withIs.proto
method:
const withIs = ; const Circle = withIs;
...or even better:
const withIs = ; { thisradius = radius;} moduleexports = withIs;
API
withIs(Class, { className, symbolName })
class
Type: class
The class to be enhanced.
className
Type: String
The name of the class your passing.
symbolName
Type: String
Unique id for the class. This should be namespaced so different classes from different modules do not collide and give false positives.
Example: @organization/package/Class
withIs.proto(Class, { className, symbolName, withoutNew })
The className
and symbolName
parameters are the same as above.
withoutNew
Type: Boolean
Default: false
Allow creating an instance without the new
operator.
Tests
$ npm test
$ npm test -- --watch
during development