简体   繁体   中英

Typescript compiled code using nested and immediate invoke function

I am trying to understand that why the following:

I have

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

and TypeScript compiler compiles it to

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

rather than

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

What are the advantages of using the nested User constructor and immediate function invocation?

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

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

you then get,

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

instead of,

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

where the chance to see that "User" (the constructor function's identifier) may give a helpful hint, while debugging something later on, or etc.

'HTH,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM