title: How to use `require` and dependency injection, service location in JS (browser-side)?
body: <p>So I've been playing with JS and <code>browserify</code> to allow to split my JS into smaller file chunks. It works great, however, I'm still lost on how to properly use the <code>require</code> function.</p>
  
  <p>For me, it acts as a the Service Locator, because it looks for the proper "file" to load, and return an object. (For example in PHP, <code>require</code> somewhat load the file in the memory but doesn't <code>construct</code>).</p>
  
  <p>Example:</p>
  
  <pre><code>var Foo = function() {
      console.log("I'm the Foo object");
  };
  
  module.exports = Foo;
  </code></pre>
  
  <p>Then, to use it I'll do:</p>
  
  <p><code>
  var Foo = require('foo');
  </code></p>
  
  <p>and</p>
  
  <p><code>
  var foo = new Foo();
  </code></p>
  
  <p>Note, that the exported function is <strong>NOT</strong> constructed.</p>
  
  <p>I could have done:</p>
  
  <p><code>
  var foo = require('foo')();
  </code></p>
  
  <p>None of those methods seems right to me (I may are wrong).</p>
  
  <ul>
  <li>1) Is it common to do it like this? Or should exported the executed function?</li>
  </ul>
  
  <p>Anyway, this introduction is to understand how I should play with the require function.</p>
  
  <p>For example if I've a Foo object, which is depends of Bar, I've two way to do:</p>
  
  <p><strong>Service Location</strong>: </p>
  
  <pre><code>var Foo = function() {
     var Bar = require('bar')();
  
     Bar.doSomethingAwesome();
  };
  
  module.exports = Foo;
  </code></pre>
  
  <p>or I can do:</p>
  
  <p><strong>Dependency Injection</strong></p>
  
  <pre><code>var Foo = function(bar) { 
     bar.doSomethingAwesome();
  };
  
  module.exports = Foo;
  
  // And at a latter time
  
  var foo = require('foo')(require('bar')); /// eurk
  </code></pre>
  
  <p>I obviously know that that's two different things and serve different purposes.</p>
  
  <ul>
  <li>2) But I'm wondering what is the common/right way to do in JS, is there any commonly admitted rules?</li>
  </ul>