An open API service indexing awesome lists of open source software.

https://github.com/kaelzhang/graceful-instanceof

The instanceof mechanism cross package/module versions.
https://github.com/kaelzhang/graceful-instanceof

class graceful instanceof nodejs

Last synced: 6 months ago
JSON representation

The instanceof mechanism cross package/module versions.

Awesome Lists containing this project

README

          

[![Build Status](https://travis-ci.org/kaelzhang/graceful-instanceof.svg?branch=master)](https://travis-ci.org/kaelzhang/graceful-instanceof)
[![Coverage](https://codecov.io/gh/kaelzhang/graceful-instanceof/branch/master/graph/badge.svg)](https://codecov.io/gh/kaelzhang/graceful-instanceof)

# graceful-instanceof

The instanceof mechanism cross package versions.

## Why?

```js
export default class MyClass {
constructor (options) {
if (this instanceof MyClass) {
return options
}

// do something with options
}
}
```

We intend to do something like this:

```js
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

```js
import bar from 'bar'
import MyClass from 'foo'

bar === new MyClass(bar) // FALSE!!

// Something BOOOOOOOOOOM !!!
```

## Install

```sh
$ npm install graceful-instanceof
```

## Usage

```js
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