1

In TypeScript, suppose there exists a simple class, Person3.

class Person3 {
    name: string
    constructor(public name: string) {
        this.name = name
    }
}

If we were writing JavaScript by hand, we might write a function like this:

var Person3 = function(name){
  this.name = name;
}

One might even go with pure function syntax:

function Person3(name){
  this.name = name;
}

But TypeScript compiles down to:

var Person3 = (function(){
  function Person3(name){
    this.name = name;
  }
  return Person3;
}());

a variable that holds an expression that holds an anonymous function. This anonymous function is contains and returns a named function whose name matches the variable's name. As far as I can tell, the anonymous function is called inline. When it is called, the named function is returned then evaluated as it is returned into the expression parenthesis.

Why do this? I'm sure there must be a reason, but I still feel like I'm having trouble truly understanding what's going on here. Why not just use name = anonymous constructer? What benefit do the nested functions give us?

Chuck Dries
  • 1,630
  • 13
  • 19

1 Answers1

2

Why do this?

The IIFE is for the case of inheritance:

class A {
}
class B extends A {
}

... is transpiled to (with an ES3/5 target):

var __extends = // ...
var A = (function () {
    function A() {
    }
    return A;
}());
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        return _super.apply(this, arguments) || this;
    }
    return B;
}(A));

Notice the parameter _super that references the parent class.

But this kind of transpilation will be obsolete soon. If we want to write JavaScript by hand, for modern JS engines, we could write:

class Person3 {
    constructor(name) {
        this.name = name
    }
}
Paleo
  • 21,831
  • 4
  • 65
  • 76