To avoid global namespace pollution.
Its a clousure pattern where inner functions have access to their parents properties. By IIFE, REFERENCE to inner functions returned.
Below are two scenarios, where IIFE pattern is quite helpful and the reason, why TypeScript Compiler generates IIFE pattern:
- Inheritance implementation: where it passes the
BaseClass
as an argument to IIFE. If IIFEE would not have been there BaseClass
would be global variable, thus polluting the global namespace.
TypeScript:
class Greeter extends BaseController {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
JS:
var Greeter = (function(_super) {
__extends(Greeter, _super);
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
};
return Greeter;
}(BaseController));
- Module pattern implementation: where app has only one global variable like 'app' and all other features are wrapped into objects like
app.cart
, app.catalog
etc. There only variable is exposed through modules and all other features are added to the modules itself, which is possible by IIFE only.
TypeScript:
module App.Controller {
export class Greeter extends BaseController {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
}
JS:
var App;
(function (App) {
var Controller;
(function (Controller) {
var Greeter = (function (_super) {
__extends(Greeter, _super);
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
}(BaseController));
Controller.Greeter = Greeter;
})(Controller = App.Controller || (App.Controller = {}));
})(App || (App = {}));
Copy/Paste this js code to browsers console and only App variable will be globally created. Rest functionality will be under App.
Thanks,
mkdudeja