https://github.com/lamansky/abstract-class
[Node.js] Prevents instantiation of a parent class. Optionally defines properties that must be implemented by child classes.
https://github.com/lamansky/abstract-class
Last synced: about 2 months ago
JSON representation
[Node.js] Prevents instantiation of a parent class. Optionally defines properties that must be implemented by child classes.
- Host: GitHub
- URL: https://github.com/lamansky/abstract-class
- Owner: lamansky
- License: mit
- Created: 2018-02-04T11:34:16.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-02-04T11:35:19.000Z (over 8 years ago)
- Last Synced: 2024-09-23T09:18:03.953Z (almost 2 years ago)
- Language: JavaScript
- Size: 1.95 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license.txt
Awesome Lists containing this project
README
# abstract-class
Prevents instantiation of a parent class. Optionally defines properties that must be implemented by child classes. Imitates the functionality provided by abstract classes in languages like Java, PHP, and C++.
## Installation
Requires [Node.js](https://nodejs.org/) 6.0.0 or above.
```bash
npm i abstract-class
```
## API
The module exports a single function. This function should be called in the constructor of the class you want to declare abstract.
### Parameters
1. Bindable: `cls` (Function): The abstract parent class.
2. `obj` (Object): The `this` variable of your object being constructed.
3. Optional: `...props` (any number of: string, number, symbol, or Array thereof): The keys of the properties that a child class should implement.
### Return Value
The function does not return a value.
## Example
```javascript
const enforceAbstractClass = require('abstract-class')
class Parent {
constructor () {
enforceAbstractClass(Parent, this, 'title', 'content')
}
}
class Child extends Parent {
get title () { return 'Title' }
}
// Throws Error: Cannot instantiate abstract class `Parent`
const parent = new Parent()
// Throws Error: `Child` must define the abstract property `content`
const child = new Child()
```
Constructing a `Parent` object fails because the class is marked abstract. Constructing a `Child` object also fails because `Child` does not define `content`.
You can also use the bind operator pattern:
```javascript
const Abstract = require('abstract-class')
class Parent {
constructor () {
Parent::Abstract(this)
}
}
// Throws Error: Cannot instantiate abstract class `Parent`
const parent = new Parent()
```
## Limitation
If the child class provides its own constructor and fails to call the parent constructor, property abstraction will not be enforced.