title: Why embed the JavaScript class in an anonymous function() call?
body: <p>I was reading about the new JavaScript-like language from Microsoft called <a href="http://www.typescriptlang.org/" rel="noreferrer">TypeScript</a>. In the <a href="http://www.typescriptlang.org/Playground/" rel="noreferrer">playground (example section)</a>, there is a simple class in TypeScript syntax converted to JavaScript code. Coming from a Java programming background, it was interesting for me to learn how OOP is done in JavaScript as compiled from TypeScript.</p>
  
  <p>The TypeScript code:</p>
  
  <pre><code>class Greeter {
      greeting: string;
      constructor (message: string) {
          this.greeting = message;
      }
      greet() {
          return "Hello, " + this.greeting;
      }
  }   
  
  var greeter = new Greeter("world");
  
  var button = document.createElement('button')
  button.innerText = "Say Hello"
  button.onclick = function() {
      alert(greeter.greet())
  }
  
  document.body.appendChild(button)
  </code></pre>
  
  <p>And the equivalent JavaScript code:</p>
  
  <pre><code>var Greeter = (function () {
      function Greeter(message) {
          this.greeting = message;
      }
      Greeter.prototype.greet = function () {
          return "Hello, " + this.greeting;
      };
      return Greeter;
  })();
  var greeter = new Greeter("world");
  var button = document.createElement('button');
  button.innerText = "Say Hello";
  button.onclick = function () {
      alert(greeter.greet());
  };
  document.body.appendChild(button);
  </code></pre>
  
  <p>The Typescript part is very similar to Java so I understand that. Now my question is why in JavaScript the body of the <code>Greeter</code> class is embedded in a an anonymous <code>function()</code> call?</p>
  
  <p>Why not write it like this?</p>
  
  <pre><code>function Greeter(message) {
      this.greeting = message;
  }
  Greeter.prototype.greet = function () {
      return "Hello, " + this.greeting;
  };
  </code></pre>
  
  <p>What is the advantage/disadvantage of each method?</p>