Typescript compiled code using a nested and immediate call function

I am trying to understand why the following:

I have

class User {
    wow:String = "xxx";
}
Compiler

and TypeScript compiles it into

var User = (function () {
    function User() {
        this.wow = "xxx";
    }
    return User;
}());

but not

var User = function() {
    this.wow = "xxx";
};

What are the benefits of using a nested User constructor and calling a function directly?

+4
source share
1 answer

There may be several good reasons, but I suspect one of them is that if you execute the following simple old JavaScript (via TypeScript output from the compiler):

var john = new User();
console.log("John constructed with: " + john.constructor);

You'll get

John constructed with: function User() {
    this.wow = "xxx";
}

instead of <

John constructed with: function() {
    this.wow = "xxx";
}

where it becomes possible to see that the "User" (identifier of the constructor function) can give a useful hint, while debugging something later, etc.

'NTN,

+3

All Articles