graceful-instanceof

1.0.1 • Public • Published

Build Status Coverage

graceful-instanceof

The instanceof mechanism cross package versions.

Why?

export default class MyClass {
  constructor (options) {
    if (this instanceof MyClass) {
      return options
    }
 
    // do something with options
  }
}

We intend to do something like this:

const instance = new MyClass(options)
 
instance === new MyClass(instance)  // true

But what happens if the instance is came from another version of the module?

abc.js
node_modules
  |-- foo # version 1.0.0
        |-- index.js # which export default MyClass
  |-- bar
        |-- node_modules # version 1.1.0
        |     |-- foo
        |           |-- index.js # also exports MyClass
        |-- index.js # which exports default the instance of MyClass

And in abc.js

import bar from 'bar'
import MyClass from 'foo'
 
bar === new MyClass(bar)  // FALSE!!
 
// Something BOOOOOOOOOOM !!!

Install

$ npm install graceful-instanceof

Usage

import instanceOf from 'graceful-instanceof'
 
const type = instanceOf('foo:MyClass')
 
class MyClass {
  constructor (options) {
    if (type.is(options)) {
      return options
    }
 
    type.attach(this)
  }
}
 
const instace = new MyClass(options)
 
instance === new MyClass(instance)  // true

And it also works cross versions.

License

MIT

Package Sidebar

Install

npm i graceful-instanceof

Weekly Downloads

199

Version

1.0.1

License

MIT

Last publish

Collaborators

  • kael