Write es6 like classes in es5 with a few more features
Cover some limitations to the current implementation of classes in es6:
- define properties
- use traits
var newClass = require('esnext-class').newClass;
var A = newClass({
constructor: function A(value) {
this.initialized = value;
}
});
var B = newClass({
name: 'B',
extends: A,
constructor(value) {
assert.strictEqual(this.constructor, B);
this.bValue = value;
}
});
name
: set the name of the classabstract
: set the class as abstractconstructor
: this is the constructor of the class, like the constructor function in es6 classesextends
: extends a class from another or from an objectimplements
: light checks over expected implementations and warn eventually when something is missingprototype
static
: define static properties in the classwith
: an array of traits, objects with properties
Properties are defined in the prototype. If you want to set a property in the instance, use the constructor to do that.
If you want to define a property in the object, use static
.
You can set constant properties like this:
var A = newClass({
name: 'A',
constantProperty: newClass.const('myValue');
});
A.prototype.constantProperty = 'anotherValue'; // Error !
var A = newClass({
name: 'A',
lazyProperty: newClass.lazy(() => 'expensive result');
});
var a = new A();
console.log(a.lazyProperty); // the result of the function is set in `a.lazyProperty`
var A = newClass({
name: 'A',
lazyAndConstProperty: newClass.lazyConst(() => 'expensive result');
});
var a = new A();
console.log(a.lazyAndConstProperty); // the result of the function is set in `a.lazyProperty`
Note: both the prototype function and the instance property values are constants.