1.0.1 • Published 6 years ago

graceful-instanceof v1.0.1

Weekly downloads
69
License
MIT
Repository
github
Last release
6 years ago

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