ES6 Class compilation to ES5 function constructor

37 Views Asked by At

I noticed something while playing with Typescript's compiler options. (Typescript is irrelevant here, I'm just using it as a compiler much like babel)

So, I have this code in .ts file

(function () {
  class Person {
    name: string;

    constructor(n: string) {
      this.name = n;
    }
  }

  const jack = new Person("Jack");
  console.log(jack.name);
})();

When I run the compiler (I set the output to es5) , it gives me this:

"use strict";
(function () {
    var Person = /** @class */ (function () {
        function Person(n) {
            this.name = n;
        }
        return Person;
    }());
    var jack = new Person("Jack");
    console.log(jack.name);
})();

The Class is converted to constructor function, as expected.

But why does it need to be wrapped in an immediately invoked function expression (IIFE)? Wouldn't a simpler version, like the one below, suffice?

"use strict";
(function () {
    
      function Person(n) {
          this.name = n;
      }
    var jack = new Person("Jack");
    console.log(jack.name);
})();

0

There are 0 best solutions below