4

I was having a look at the JS code generated by TypeScript on this page:

http://www.typescriptlang.org/Playground/

Basically, to create a Greeter class, it outputs this:

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

var greeter = new Greeter("world");

So I'm wondering why they are mixing the module and prototype pattern? Wouldn't it be the same just to do:

function Greeter(message) {
    this.greeting = message;
}

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

var greeter = new Greeter("world");

?

5
  • It would be exactly the same if you used var Greeter = function(message)... in your second code Commented Jan 14, 2013 at 3:23
  • @zerkms, you mean the extra code they put has no purpose? Commented Jan 14, 2013 at 3:26
  • in this case - there is no reason for that. But they provide a general solution. Commented Jan 14, 2013 at 3:56
  • 1
    Perhaps part of the reason is that it looks better: it has a nice "Greeter" constructor method, which is like C# (name of the class), and also, it keeps the "class definition" all together (within the same {}) while avoiding duplicating the function objects for each instance (it might redefine them every time, but at least there will only be 1, not many copies of the class function objects) Commented Jun 3, 2015 at 18:07
  • @zerkms It would not be "exactly" the same. The OP's example function Greeter(message) {...} would be hoisted, whereas your example would not. Commented Nov 9, 2016 at 11:09

1 Answer 1

7

The use of module pattern here is to create a closure, allowing for more control over any closed over variables (nothing leaking into global, no global pollution), and allowing for the creation of 'private' variables (variables that only exist via the module pattern's closure).

Sign up to request clarification or add additional context in comments.

3 Comments

What private variables though? TypeScript doesn't use closures to implement private access.
I didn't realize it didn't have privates, but the _super in the "Simple Inheritance" example on the Playground is doing effectively the same thing (capturing a "private" _super variable via closure).
Yes, also non-exported module members are obscured in closures. However, back to the original question - there doesn't seem to be a legitimate use case for 'module pattern' in TypeScript's implementation of classes. They could have done without it and lose no functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.