Behold the mighty TypeScript class:
class Saluter {
public static what(): string {
return "Greater";
}
public target: string;
constructor(target: string) {
this.target = target;
}
public salute(): string {
return "Greetings, " + this.target;
}
}
When TS aims for ES5, it morphs into an IIFE:
var Saluter = /** @class */ (function () {
function Saluter(target) {
this.target = target;
}
Saluter.what = function () {
return "Greater";
};
Saluter.prototype.salute = function () {
return "Greetings, " + this.target;
};
return Saluter;
}());
Nevertheless, it behaves similarly when presented as a traditional constructor function. It looks more like JavaScript in its natural state :)
function Saluter(target) {
this.target = target;
}
Saluter.what = function () {
return "Greater";
};
Saluter.prototype.salute = function () {
return "Greetings, " + this.target;
};
Application:
Both versions function identically:
Greater.what(); // -> "Greater"
var greeter = new Greater("Universe!");
greeter.greet(); // -> "Hello, Universe!
What are the advantages or reasons for wrapping it in an IIFE?
I conducted a basic benchmark test:
console.time("Saluter");
for(let i = 0; i < 100000000; i++) {
new Saluter("world" + i);
}
console.timeEnd("Saluter");
The results exhibited virtually identical instantiation speeds. This is expected since the IIFE is only resolved once.
I pondered if it might be due to closure, but the IIFE doesn't accept arguments. So, it cannot be a closure.