An ES6-inspired API to create "classes" in ES5.
Features
- Class
- (Multiple) Inheritance
- Abstract method/class
- Getters & setters
- Static
[Object.]classFactory([parents, ] definition)
Returns a class (i.e. function).
parents
: [optional] Parent classes (i.e. function) in the form of an array.definition
: A callback function used to create the class.
Class Object
The class obejct created by classFactory
contains the follows properties:
constructor
: The class constructor.definition
: The function used to define the class.parents
: An array of parent class object.abstract
: All abstract methods.get
: Getters.set
: Setters.create(...)
: The method for creating instances.
Class Instance
Each instance of class contains a .instanceOf(classObject)
function, which allows to check if an object is the instance of a class.
Examples
In browser:
var Person = Object; var guy = Person;guy; // Someoneguy; // 10 var Coder = Object; var monkey = Coder;monkey; // Code Monkeymonkey; // 20monkey; // JavaScript monkey; // truemonkey; // true
In Node.js:
You can import classFactory by, for example, var classFactory = require('class-factory-js');
. Then var Person = classFactory(...)
.
Getters & Setters
Getters & setters can be defined through this.get
and this.set
in the class definition callback function.
For example:
var Person = Object; var p = Person;pinfo; // 'Superhero -- 1'pinfo = 'Superman';pname; // 'Superman'
Static
static
is supported by using this.static
.
For example:
var Person = Object; Persontype; // 'Human'Person; // 'Hi'
Abstract methods
The below example shows how to define and implement abstract method. All abstract methods should be defined under this.abstract
property.
var Person = Object; Person // TypeError: Person is an abstract class. var Boy = Object; var boy = Boy;
Notice that a TypeError
will be thrown if not all the abstract methods are implemented.
License
MIT