ES5-Class
Highlights
A Class object that enables native prototypal inheritance for Node and modern browsers.
It's called class because it encapsulate your methods, provide inheritance, set static and prototype methods and variables, and provide helper functions along all your instances.
Why should we write code like if we were in 2010? Read on!
- Multiple inheritance made easy
- Support
get
,set
,__defineGetter__
,__defineSetter__
without any extra code - It's freaking fast, check the benchmark section
- Uses
Object.setPrototypeOf
(when available, using__proto__
when isn't),Object.create
andObject.defineProperty
ES5/ES6 methods to enable native prototypal inheritance with proper settings (enumerable, configurable, writable) - Works with Node.js 0.8.x and up (including node-webkit), and really modern browsers (IE11, Firefox, Chrome, Safari).
- Functions to implement other class methods and include other instance/prototype methods
- The
$implement
method imports both prototype and class methods - The
$include
method imports prototype methods, and class methods as prototype
- The
- Takes advantage of ES5 non-writable properties to disable the possibility of messing up the classes
- Ability to inherit from multiple classes using arrays using
ES5Class.$define('YourClass', [Class1, Class2, Class3])
without setting the$parent
class, working like mixins/traits - Inject and call
$super
to reach the parent instance class functions or extended class method - Call
this.$parent
to reach the parent class definition inside your methods this.$implements
array property contain all classes that were implemented into the current class instance- The
construct
method is called with arguments when the class is instantiated this.$class
is available everywhere, it returns the current class, even before instantiation- You are free to instantiate your class using
Class.$create(arguments)
,Class(arguments)
andnew Class(arguments)
Documentation
See docs in ES5Class Documentation
Breaking changes
Version 1.x had this.$super
call, but it wasn't "async safe". If you would execute it in an asynchronous (setImmediate
,
setTimeout
, inside Promises or other callbacks), this.$super
could be either undefined or be another function, since
this.$super
was a global state variable on the instance.
To solve this, the $super
(idea taken from Prototype.js) must be injected as the first parameter on your function.
Before you'd call your $super
classes like this:
var Base = ES5Class;var Sub = Base; Sub;
In version 2.x, you need to call it like:
var Base = ES5Class;var Sub = Base; Sub;
$super
is merely a shortcut for this.$parent.prototype.fn.apply(this, arguments);
(actually a bit fancier than that).
Nothing stops you from doing that by yourself (if you don't fancy the $super
argument injection)
In version 2.x you'll also need better-curry as a dependency.
Install
$ npm install es5class
$ bower install es5class
// In node.jsvar ES5Class = ; // or in the browserwindowES5Class // or with RequireJS;
Example usage
Creating a new class
var Animal = ES5Class;
Class inheritance
var Bird = Animal;
Extending the prototype
// append functions to the prototype. existing functions in the prototype are // wrapped for $super accessBird;
Add static and prototype members to the class
// "Implement" import the prototype (if it has a prototype) and class methods from the // given object, to the class declarationvar Class1 = ES5Class obj = yup: true {}; hprototypenope = false; Class1; console; // true (imported to the class declaration)console; // false (imported to the prototype)
You can call the inheriting class $super
construct by passing true to the second parameter,
for example:
var EventEmitter = EventEmitter; // this code is the same asES5Class; // this one (much cleaner)ES5Class; // There's no need for the construct + implement if you are just creating // an inheritance from another Node.js class// So it's easier to set the second parameter of implement to true, it // will call the parent class constructor automatically
Because it's really easy to forget to initialize the super constructor of the inheriting class
Include (mixin) to the current prototype
// "Implement" import class methods *ONLY* from the given object, // to the class declaration prototype *ONLY*var Class1 = ES5Class obj = yup: true {}; hprototypenope = false;hyep = false; Class1; // true (imported to the prototype)console; // undefined (not imported since it's in the prototype of the "h" object)console; // undefined (not imported since it's in the prototype of the "h" object)console; // false (imported to the prototype since it's in the declaration of the "h" object)console;
Inherit from any existing (Node.js) class
var MyEventClass = ES5Class; MyEventClass; // or MyEventClass;
Constants
var MyClass = ES5Class; MyClasscant = false; // still 'touch this' // throws exception on strict mode
Encapsulate logic by passing a closure
Bird; Bird;
Exchange the instance prototype chain
var MyEmptyClass = ESClass;MyEmptyClass; // MyEmptyClass instance now 'looks like' an Error instance
Import an object to the current instance
var MyEmptyClass = ESClass;var instance = MyEmptyClass;instance;
Enumerate members
ES5Class$names; // ['some','somefn']
Wrap an existing object or function as an ES5Class
var someRandomObject = {};var MyClass = ES5Class; // creates a new class ES5Class; // returns itself
Prototypal inheritance from another class
// These functions and values persist between class creation, serve as static methodsAnimal; var Dog = Animal;Animal; // Dog.ran and Animal.ran are 10var Cat = Animal;Cat; // Cat.ran is 20, Dog.ran and Animal.ran are 10Dog; //Dog; // Cat.ran is 20, Dog.ran is 30 and Animal.ran is 10 // If you implement the same method, you can update the parent using this.$parent// If you want to update the parent value, you can also use this.$parent.ranDog; Dog; // Dog.ran is now 40, Animal.ran and Cat.ran are now 20 // primitives are copied over to new classes (in this case, Cat and Dog)// objects retain their reference between all classes
Creating an instance
var animal = Animal;var bird = Bird;var bird2 = ;var bird3 = "Also a bird";
Checking instances
animal; // trueanimal; // falsebird; // truebird; // truebird; // true
Other useful methods and properties
Animal$className; // 'Animal'bird$class; // returns the Bird class definition, you can do a $class.$create('instance', 'params')bird$class$className // 'Bird'bird$class$parent$className // 'Animal'bird$parent$className // 'Animal'bird$parent$parent$className // 'ES5Class'bird; // trueAnimal; // false
Mixin from other classes (Object composition)
var Class1 = ES5Class Class2 = ES5Class Class3 = ES5Class; // This mix in the whole class (prototype and class methods)var NewClass = ES5Class; // Pay attention that it needs to go in the second parameter if you want// to copy the object properties AND the prototype properties // or using NewClass.$implement([Class1, Class2, Class3]); Class1done = false; // Changing the base classes doesn't change the mixin'd class console; // trueconsole; // trueconsole; // ES5Classconsole; // [Class1,Class2,Class3]console; // trueconsole; // true // This mix in class methods as prototypesNewClass = ES5Class; console; // trueconsole; // falseconsole; // undefined
Singletons
var Singleton = ES5Class; var ExtraSingleton = ES5Class;ExtraSingleton;ExtraSingleton; Singletonextra // undefinedExtraSingletonextra // trueExtraSingletonstaticVariable // 1ExtraSingleton; // 'Extrahelper'
Share data between instances (flyweight pattern)
var Share = ES5Class;var one = Share two = Share; // Share.count is now 2one; // _data is now {'dub': true}two; // _data is now {'dub': false}two; // _data is now {'dub': false, 'bleh': [1,2,3]}
Duck typing (nothing stops you to not using inheritance and decoupling classes)
var Op = ES5Class; var Mul = Op; var Div = Op; var Sum = Op; var Operation = ES5Class; var sum = Sum; var mul = Mul; var div = Div; Operation; Operation; // Result is 350 var mul2 = Mul; Operation; // Result is 67500
For a lot of class examples (inheritance, extending, singletons, etc), check the test sources at test/class-test.js
Performance tip
Although the class helpers, $super
calls, class inheritance itself are fast, $define
'ing your class isn't.
For some odd reason, Object.defineProperties
and Object.defineProperty
is long known to have the worst performance in V8
(and other engines as well).
Basically, you should never keep redefining your class, for example, in loops, inside other constructors, etc.
The ES5Class.$define
is a real bottleneck (as low as 10k ops/s). So, $define
it once, create instances everywhere!
Running the tests
The tests are ran using mocha
$ npm install && npm run test
Benchmark
Check how this library perform on your machine
$ npm install && npm run benchmark
A benchmark result in a 1st gen Core i3:
class instance function call x 125,269,746 ops/sec ±10.00% (34 runs sampled)
class method function call x 123,280,719 ops/sec ±4.17% (40 runs sampled)
class instance included function call x 103,738,852 ops/sec ±3.78% (42 runs sampled)
$super instance function calls x 14,187,910 ops/sec ±0.44% (96 runs sampled)
$super class function calls x 13,874,190 ops/sec ±0.73% (96 runs sampled)
$super inherited two levels deep function calls x 6,910,075 ops/sec ±0.40% (100 runs sampled)
class.$create instantiation x 1,832,552 ops/sec ±1.69% (91 runs sampled)
new operator x 4,544,620 ops/sec ±0.37% (98 runs sampled)
obj() instance x 1,225,367 ops/sec ±2.45% (96 runs sampled)
ES5Class.$define x 12,106 ops/sec ±2.73% (85 runs sampled)
Feeback
Please use the issues section of github to report any bug you may find
Contributors
License
(The MIT License)
Copyright (c) 2011 Bruno Filippone
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.