instanceof-unifier
Allow instanceof
to match even if comparing an instance created by a different
copy of the class. This module requires node.js 6.5.0 or above to function, an
exception will be thrown if you attempt to load this module in older versions.
instanceofUnifier(Class, matcher)
Calling this function makes alterations to the way instanceof
works on Class
.
matcher
must be a string
.
The user is responsible for picking a unique matcher name. It is recommended to use
<module-name>@<version>:package-local-id
. Version does not have to match the package
version but it is important to increment it any time a version update is not compatible
with previous versions.
Example Usage
Create an ESM module:
// index.mjs; ;
Transpile to Commonjs (babel output shown):
// index.cjs"use strict"; Object;exportsMyClass = void 0; var _instanceofUnifier = ; { return obj && obj__esModule ? obj : default: obj ; } {} exportsMyClass = MyClass;0 _instanceofUnifierdefaultMyClass 'my-package-name@1.0.0:MyClass';
This avoids the divergent specifier hazard for instanceof
. You can test:
;; const CJS = indexCJSMyClass; const cjs = ;const esm = ; if cjs instanceof CJS && cjs instanceof ESM console; if esm instanceof CJS && esm instanceof ESM console;
In addition to the divergent specifier hazard this also ensures instanceof
matches
between multiple copies of your module.