Search code examples
javascriptamd

How to write AMD compatible JavaScript classes?


What is the best method for writing AMD compatible JavaScript classes to be used as part of a modular app?

I usually write my classes using the singleton approach. Unless there is some trick to making it work with AMD, this does not appear to be compatible.


Solution

  • Well, we use AMD, and most of our files are singletons. We actually don't really declare a 'class' to only be used once (singleton) - we specifically define the one object instance, though to some people that's just a technical distinction. Here's an example:

    // mylib.js
    define(["otherlib"],
    
    function(otherlib) {
    
    return {
      doThing: function() {
        return otherlib.action("thing");
      }
    };
    });
    

    In case you're wondering: Requiring this file 7 times will actually return the very same object each time - it won't get recreated.