I'm defining a module with the UMD style of defining a module that can be used across CommonJS, AMD, and browser globals like so:
(function (root, factory) {
if (typeof define === 'function' && define.amd) define(['exports'], factory);
else if (typeof exports === 'object') factory(exports);
else factory(root.GlobalObject = {});
})(this, function (exports) {
// Module definition here
});
This is great for if I want to attach properties to the exported object, but what if I want to just return a single constructor function from this definition and have all three systems able to load up this module and directly use the function returned, rather than having to return an object literal and access the constructor as a property of the literal?
That’s impossible, just by the specification of the very first item on your list.
Module Context
- In a module, there is a free variable "require", which conforms to the above definiton [sic].
- In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
- modules must use the "exports" object as the only means of exporting.
- In a module, there must be a free variable "module", that is an Object.
- The "module" object must have a "id" property that is the top-level "id" of the module. The "id" property must be such that require(module.id) will return the exports object from which the module.id originated. (That is to say module.id can be passed to another module, and requiring that must return the original module). When feasible this property should be read-only, don't delete.
- The "module" object may have a "uri" String that is the fully-qualified URI to the resource from which the module was created. The "uri" property must not exist in a sandbox.
That is to say, exports
is an object; it must be the only object by which methods can be exported; and you can only add to it.