0

I've been playing with TypeScript, and I notice it follows a particular style with JS.

The following TypeScript:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

Generates JS like this:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

What's the benefit of the IIFE? Why do I need to attach my methods to my prototype in a new scope?

Do I lose anything if I continue to do:

function Greeter(message) {
    this.greeting = message;
}
Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
};

(as I have always done) instead?

Charles
  • 50,943
  • 13
  • 104
  • 142
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • @jfriend00 Yep I'd agree, the answer for that answers this one perfectly. – mikemaccana Mar 28 '14 at 18:00
  • 1
    I am not familiar enough with TypeScript to say, but it might be that it will sometimes add additional local state, and for simplicity's sake it just uses the same IIFE structure regardless of whether the conditions that require local state are present. – Chuck Mar 28 '14 at 18:07

0 Answers0