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.
- Host: GitHub
- URL: https://github.com/kaelzhang/graceful-instanceof
- Owner: kaelzhang
- License: other
- Created: 2018-01-09T03:45:36.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-01-10T07:24:31.000Z (almost 8 years ago)
- Last Synced: 2025-03-25T13:16:16.434Z (7 months ago)
- Topics: class, graceful, instanceof, nodejs
- Language: JavaScript
- Homepage:
- Size: 5.86 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- License: LICENSE-MIT
Awesome Lists containing this project
README
[](https://travis-ci.org/kaelzhang/graceful-instanceof)
[](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