10

Let's have, for example, a Dog class:

class Dog {
    static food;
    private static static_var = 123;

    constructor(private name) {}

    speak() {
        console.log(this.name + ', I eat ' + Dog.food + ', ' + Dog.static_var);
    }
}

Compiled to JS:

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

    Dog.prototype.speak = function () {
        console.log(this.name + ', I eat ' + Dog.food + ', ' + Dog.static_var);
    };

    Dog.static_var = 123;
    return Dog;
})();

This works equally well and is less complicated:

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

Dog.prototype.speak = function () {
    console.log(this.name + ', I eat ' + Dog.food + ', ' + Dog.static_var);
};

Dog.static_var = 123;

Is there any (other than "aesthetic") reason for using the anonymous function wrapper?

MightyPork
  • 18,270
  • 10
  • 79
  • 133

1 Answers1

6

The main difference between the two has to do with hoisting.

TypeScript compiles the class into an assignment of a function expression to a variable. That means the resulting constructor only starts to exist at the point of assignment. In the code that occurs before, Dog will be bound to undefined.

On the other hand, your implementation uses a plain function that is subject to hoisting -- any code in that scope, including code that occurs before the function, can invoke the Dog constructor.

I guess TypeScript prefers to ensure that a class does not exist before it is actually defined, possibly to allow redefining the class at several points in the same scope.

Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479