title: Module pattern in JavaScript for custom constructors
body: <p>I am trying to apply module pattern in JavaScript when I have my custom constructor. Let us take this example:</p>
  
  <pre><code>// Assume I need `name` as private
  function Dog(name){
      this.name = name;
  }
  </code></pre>
  
  <p>I can rewrite above as:</p>
  
  <pre><code>function Dog(name) {
  
      let dogName = name;
  
      return {
  
          getName : function () {
              return dogName;
          },
  
          setName : function (name) {
              dogName = name;
          }
      }
  }
  </code></pre>
  
  <p>The above code does not have right <code>constructor</code> property and <code>Dog.prototype</code> and the <code>prototype of object returned</code> <em>does not match</em>.</p>
  
  <p>To fix this I made 2 Fixes:</p>
  
  <pre><code>function Dog(name) {
  
      let dogName = name;
  
      return {
  
          // Fix 1
          constructor : Dog,
  
          getName : function () {
              return dogName;
          },
  
          setName : function (name) {
              dogName = name;
          }
      }
  }
  
  
  let d2 = new Dog("Tony");
  // Fix 2 : This is painful as every time I need to set this up
  Object.setPrototypeOf(d2 , Dog.prototype);
  </code></pre>
  
  <p>As you can see Fix 2 is painful. Every time I have to create an object, I need to do this.
  Is there any better way? </p>
  
  <p>Let us not deviate our discussion that getter and setter should be moved to prototype. Above is just a quick example I am using.</p>