这是一个使用模块作为架构的非常简单的示例:
<!DOCTYPE html>
<title>Module play</title>
<body>
<script>
// myCore provides all functionality required by modules
// Could use a library in here
var myCore = {
  getContainer: function() {
    // code in here to find a suitable container in which to put widgets
    // This is where different client capabilities will be tested to ensure the
    // widget behaves in it's user agent context - desktop, phone, tablet, pad, etc.
    // very simple shortcut
    return {
            element: document.body,
            // This function could use a general purpose library
            add: function(widget) {
              this.element.appendChild(widget.getElement());
            }
    };
  },
  // This function could use a general purpose library
  getNewWidget: function() {
    var element = document.createElement('div');
    return {
      getElement: function() {
        return element;
      },
      display: function(text) { 
        // Tightly couple to itself or not? 
        this.getElement().innerHTML = '<em>' + text + '</em>';
        // or
        element.innerHTML = '<em>' + text + '</em>';
      }
    }
  }
};
// Missing sandbox layer...
// Add a module - only uses myCore API (access should be controlled by
// the sandbox), does not deal with underlying library or host objects
(function() {
  // Get a container to add a widget too
  var container = myCore.getContainer();
  // Create a widget
  var widget = myCore.getNewWidget();
  // Add the widget to the container
  container.add(widget);
  // Give something to the widget to display
  widget.display('Hello World');
}());
</script>
</body>
所以你可以看到,在模块级别,你并不关心宿主环境或底层库,你只是在编写普通的 ECMAScript。你可以得到真正的防守并做一些事情,比如:
(function() {
    var container, widget;
    if (!myCore) return;
    if (myCore.getContainer) { // Some would include an isCallable test too
      container = myCore.getContainer();
    }
    // getWidget could be a method of container instead so that
    // everything you need is either a method or property of container
    // or widget
    if (myCore.getWidget) {
      widget = myCore.getWidget();
    }
    ...
}
依此类推,一切都经过测试和检查。我省略了错误处理,但希望这个例子就足够了。