title: Dependency injection in javascript
body: <p>I have been playing around with dependency injection with javscript but have some questions that I need help with</p>
  
  <p>A simple example is a dialog module I have, used in multiple places on the page it alerts a user with a custom message when a user interacts with a component on the page</p>
  
  <pre><code>function Dialog () {
  
  }
  
  Dialog.prototype.show = function () {
  
  }
  </code></pre>
  
  <p>and this may be used in a component, say a search control which validates a user search and if its empty it fires an error dialog. With dependency injection I'm assuming I would write:</p>
  
  <pre><code>function searchComponent (dialog) {
     this.dialog = dialog
  }
  
  searchComponent.prototype.validateSearch = function () {
      // validate search if invalid create error
      this.dialog.show();
  }
  
  var searchDialog = new Dialog();
  var search = new searchComponent(searchDialog);
  </code></pre>
  
  <p>However a user may never need the search error dialog, yet I am creating an instance of it just so that I can then pass the dependency through, what if I have 100 individual instances of a dialog on the page do I construct these 100 times, this is unnecessary and expensive in performance.</p>
  
  <p>what I would rather do is lazy load the construction of a dialog to a time when it is needed</p>
  
  <pre><code>searchComponent.prototype.validateSearch = function () {
    //validate search if invalid create error
    var dialog = new Dialog();
    dialog.show();
  }
  </code></pre>
  
  <p>now I know that this creates disadvantages and one of these is the affects it has on unit testing, what I am keen to understand is whether I have missed something or an alternative method?</p>
  
  <p>Thanks in advance</p>