It is possible with JavaScript to treat classes and modules as functions with dependencies using the function’s prototype. We can say that a class extends classes, but to make the similarities of modules and classes a little clearer I will say that a class depends on classes. We could also say that a module imports modules, or we could say that a module depends on modules.
Below is an example of what I’m going to call a “unit”, a unit can depend on other units and can be ran and used like a module, or used to construct objects like a class. This particular unit called `myUnit` has no dependencies and contains one method called `myMethod`.
(this.myUnit = function myUnit() { var self = {}; self.myMethod = function () { return 'hello world'; }; return self; }).prototype = { // Has no dependencies. };
This second unit called `testMyUnit` is unsurprisingly used to test the unit defined above. This unit depends on `myUnit` and has one method called `run` which can be used to run the tests. The `run` method attempts to use `myUnit` as a module by executing `myUnit`and calling a method, it also attempts to use `myUnit` as a class and this can be done two ways, (1) using the `new` keyword, and (2) using `Object.create`. Calling this units `run` method should return 0 if all tests pass.
(this.testMyUnit = function testMyUnit() { var self = {}; var myUnit = testMyUnit.prototype.myUnit; self.run = function () { var expectResult = 'hello world'; var testModule = myUnit().myMethod() === expectResult; var testNew = (new myUnit).myMethod() === expectResult; var testCreate = Object.create(myUnit()).myMethod() === expectResult; // Returns the number of failed tests. return Number(!testModule) + Number(!testNew) + Number(!testCreate); }; return self; }).prototype = { // Depends on myUnit. myUnit: myUnit }; testMyUnit().run();
I think this an interested pattern and could be of some use to JavaScript developers.