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.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();