TypeScript compiles a class something like:
var UrlProvider = (function(){
//tons of logic in here that only needs to be performed once for each Url
IS there any benefit to putting logic in outside the constructor, but inside the IIFE
Yes. The IIFE is needed for inheritance to capture the base class. This is shown below
class Foo {
log() { }
}
class Bar extends Foo {
log() {
super.log(); // IIFE needed for `super` to work
}
}
Look at the generated javascript (I've removed the extends function).
var Foo = (function () {
function Foo() {
}
Foo.prototype.log = function () {
};
return Foo;
})();
var Bar = (function (_super) {
__extends(Bar, _super);
function Bar() {
_super.apply(this, arguments);
}
Bar.prototype.log = function () {
_super.prototype.log.call(this); // IIFE needed for `super` to work
};
return Bar;
})(Foo);
_super
is captured by the IIFE. Reason is that functions are the only thing that create a variable scope in JavaScript and that is why we create an IIFE in the codegen to capture the base class in a nice local name (_super
). This is conventional JavaScript, not specific to TypeScript.