I am developing a javascript library and would like to store groups of optional methods on a Javascript object in different modules.
The library has two modules, lets call them ModuleA and ModuleB. ModuleA exports a class object, lets call it ClassA, that only has minimal, core functionality. ModuleB defines a set of optional methods to be set on the prototype of ClassA.
In a third module not in the library, ModuleC, I would like the following:
If I import only ModuleA and instantiate ClassA, I know I have access to all ModuleA methods on InstanceA using 'InstanceA.MethodA(...)'. (Other methods may be defined on InstanceA as well)
If I import both ModuleA and ModuleB and instantiate ClassA, I know I have access to all ModuleA methods as well as ModuleB methods on InstanceA using 'InstanceA.MethodA(...)' and 'InstanceA.MethodB(...)'.
I have considered a few solutions but am unsure if there is a preferred way to accomplish this. Here is what I have considered:
ModuleB alters ClassA The factory for ModuleB import ModuleA and alters ClassA. Would these changes be guaranteed to persist? Does AMD guarantee importing the same module across an environment always returns the same object?
ModuleB returns altered ClassA ModuleB extends ClassA and returns new Object. This would probably work fine in this example with only two modules, but what about with multiple optional method modules?
Please let me know if you have encountered a similar situation and what your solution was.
here is my approach:
// Module A - Define ClassA
define(function() {
function ClassA() {}
ClassA.prototype.methodA = function() {};
return ClassA;
});
// Module B - Extend
define(function() {
return function(ClassToExtend) {
ClassToExtend.prototype.methodB = function() { };
};
});
// Module C - Sticking
define(function(require) {
// Define ClassA
var ClassA = require("module_a");
// Extend ClassA with custom methods of ModuleB
require("module_b")(ClassA);
// Instanciate extended ClassA
var InstanceA = new ClassA();
}