toy-es5-class
v0.0.1
Published
Syntactic sugar for classes in pure ES5
Downloads
2
Readme
Description
Little toy to define classes in pure ES5 (EcmaScript 5) in a way that looks as similar as possible to the ES2015/2016 class definition syntax. It isn't 100% spec-compliant (and can't be), but should be close enough.
If you're not familiar with ES2015 classes, check this guide.
Installation
npm i toy-es5-class
# or
bower i toy-es5-class
# or whatever package management solution you use...
In a module loader, require the package:
var Class = require('toy-es5-class');
If neither 'require' nor 'define' is detected, it will globalise itself
automatically as window.Class
.
Usage
Sample class definition:
var Pokemon = Class({
// Initialisation.
constructor() {
this.sound = 'Pika!';
}
// Instance method.
noise: function() {
console.log(this.sound);
},
// Static method.
'static spawn': function() {
return new this();
}
});
Inherit from another class:
var Charmander = Class({
extends: Pokemon,
constructor() {
this.sound = 'Charr!';
}
});
console.log(new Charmander().noise()); // 'Charr!';
console.log(Charmander.spawn().noise()); // 'Charr!';
Additional notes:
- The 'constructor' function is optional. If omitted, it's created automatically.
- The subclass always calls the superclass before calling the constructor, passing all arguments.
- The class must always be called with
new
. - Getters and setters are supported.
Compatibility
Should work in any ES5 environment (IE9 and above).